GCDAsyncSocket server receive data only first time

前端 未结 2 661
广开言路
广开言路 2021-02-04 18:18

Client sent message every time when I press send button but Server receive message only first time. What is the issue in server

Server:

         


        
2条回答
  •  鱼传尺愫
    2021-02-04 18:51

    so after struggling with this for a bit, I came up with the following pattern for digesting data. Though the below is an over simplification, it is easily ported to different tasks:

    Somewhat Swift Solution 
    
    var dataCache = Data()
    
    func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
        sock.readData(withTimeout: -1, tag: 0)
    }
    
    func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
        dataCache.append(data)
        sock.readData(withTimeout: -1, tag: 0)
    }
    
    func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
        print("Closed with error: \(err)")
        processData()
    }
    
    func socketDidCloseReadStream(_ sock: GCDAsyncSocket) {
        print("Closed successfully")
        processData()
    }
    
    func processData() {
        // Do something with dataCache eg print it out:
        print("The following read payload:\(String(data:dataCache, encoding: .utf8) ?? "Read data invalid")")
        dataCache = Data()
    
    }
    

提交回复
热议问题