I'm creating a functionality which allows you to share pictures between iOS Devices and other computer in one local network.
I bumped into a problem when I'm writing data to a socket, but it's not being delivered until I close the connection. As I know there should be something like flush()
method. Because its behaviour acts as it happens when I'm disconnecting.
So it would be perfect if somebody can help or suggest better solution for that problem.
Here is my manager class:
import CocoaAsyncSocket
class CollaborationSocketConnectionService: NSObject, GCDAsyncSocketDelegate {
static let shared = CollaborationSocketConnectionService()
var tcpSocket: GCDAsyncSocket?
private var ipAddress = ""
private var port = 0
private var guid = String()
override init() {
super.init()
tcpSocket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
guid = UUID().uuidString.lowercased()
}
// MARK: - General Functions
func connectToSocket(at ip: String, port: Int) {
self.ipAddress = ip
self.port = port
do {
try tcpSocket?.connect(toHost: ip, onPort: UInt16(port), withTimeout: -1)
} catch let error {
print("Cannot open socket to \(ip):\(port): \(error)")
tcpSocket = nil
}
}
func disconnect() {
tcpSocket?.disconnect()
}
func sendImage(image: UIImage?) {
if !(tcpSocket?.isConnected ?? false) {
try? tcpSocket?.connect(toHost: self.ipAddress, onPort: UInt16(self.port), withTimeout: -1)
}
guard let data = image?.jpegData() else {return}
let base64Image = data.base64EncodedString()
let imageModel = UploadImage(contentLength: 666, command: "UploadImage", uuid: guid, imageData: ImageData(fileSize: base64Image.count, fileGuid: UUID().uuidString.lowercased(), blocksCount: 1, blockIndex: 0, blockLength: base64Image.count, data: base64Image))
let encoder = JSONEncoder()
let jsonData = try? encoder.encode(imageModel)
self.tcpSocket?.write(jsonData!, withTimeout: 10, tag: 1)
}
// MARK: - GCDAsyncSocketDelegate
func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
print("connected")
sock.readData(withTimeout: -1, tag: 0)
}
func socket(_ sock: GCDAsyncSocket, didWritePartialDataOfLength partialLength: UInt, tag: Int) {
if tag == 0 {
print("written")
}
}
func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) {
if tag == 0 {
print("First Chunk sent")
// self.tcpSocket?.disconnect()
// self.tcpSocket?.perform {
// self.tcpSocket?.disconnectAfterWriting()
// }
// self.connectToSocket(at: self.ipAddress, port: self.port)
}
if tag == 1 {
print("Second Chunk sent")
}
if tag == 99 {
print("KEK")
}
}
func socket(_ sock: GCDAsyncSocket, didReadPartialDataOfLength partialLength: UInt, tag: Int) {
print(partialLength)
}
func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
let stringFromServer = String(bytes: data, encoding: .utf8)
print("READED DATA \(stringFromServer!)")
}
func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
print("DISCONNECTED")
}
And I figured out with the solution. Just add "\n" to the end of your message...
let jsonDataString = String(bytes: try! encoder.encode(imageModel), encoding: .utf8)! + "\n"
let jsonData = jsonDataString.data(using: .ascii)