GCDAsyncSocket 不向 TCP 套接字服务器发送数据

GCDAsyncSocket doesn't send data to TCP Socket server

我正在创建一项功能,允许您在 iOS 设备和一个本地网络中的其他计算机之间共享图片。

我在将数据写入套接字时遇到了问题,但直到我关闭连接后数据才被传送。据我所知,应该有类似 flush() 的方法。因为它的行为就像我断开连接时发生的那样。

因此,如果有人可以帮助解决该问题或提出更好的解决方案,那就太完美了。

这是我的经理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")
    }

我找到了解决方案。 只需在消息末尾添加“\n”...

let jsonDataString = String(bytes: try! encoder.encode(imageModel), encoding: .utf8)! + "\n"
let jsonData = jsonDataString.data(using: .ascii)