GCDAsyncSocket不会将数据发送到TCP套接字服务器

时间:2019-11-14 14:10:37

标签: ios swift sockets tcpclient

我正在创建一项功能,使您可以在一个局域网中的iOS设备和其他计算机之间共享图片。

当我向套接字写入数据时遇到了问题,但是直到关闭连接后才传递数据。据我所知,应该有类似flush()的方法。因为它的行为就像我断开连接时一样。

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

这是我的经理班:

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")
    }

1 个答案:

答案 0 :(得分:0)

我想出了解决方案。 只需在邮件末尾添加“ \ n” ...

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