GCDAsyncSocket server receive data only first time

非 Y 不嫁゛ 提交于 2019-12-03 03:34:21
Gandalf

You have to make a read call from your server class in didReadData: delegate. Rest is fine. Use below code.

-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {

   [sock readDataWithTimeout:-1 tag:0];

    NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"MSG: %@",msg);
}

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()

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!