GCDAsyncSocket是否可以自动readData

时间:2015-09-09 09:16:19

标签: ios sockets

我使用iPad连接到运行Python脚本的服务器。服务器将不断向iPad发送消息。但是间隔不是一个常数。 当我称这种方法时:

[newSocket readDataWithTimeout:-1 tag:0];

我可以从服务器获取我想要的消息:

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

但我的问题是,我必须经常拨打readDataWithTimeout,就像在NSTimer中一样。或者,如果服务器发布消息,我的客户端/ iPad可以自动获取消息。

谢谢!

1 个答案:

答案 0 :(得分:3)

您只需要拨打一次电话,但是当调用socket:didReadData:withTag:时,如果您需要更多数据,则需要再次拨打readDataWithTimeout:

我躺在一个例子(快速):

func socket(sock: GCDAsyncSocket!, didAcceptNewSocket newSocket: GCDAsyncSocket?) {
    println("new connection recieved \(newSocket?.hash) old: \(sock?.hash)");

    socketRead = newSocket;

    self.socketRead?.readDataToData(self.dataDelimiter, withTimeout: -1, tag: 0) //start reading
}

func socket(sock: GCDAsyncSocket!, didReadData data: NSData!, withTag tag: Int) {

    var mutableData:NSMutableData = NSMutableData();
    mutableData.appendBytes(data.bytes, length: data.length-dataDelimiter.length) //remove delimiter
    var error:NSError?
    var jsonDic:NSDictionary? = NSJSONSerialization.JSONObjectWithData(mutableData, options: NSJSONReadingOptions.allZeros, error: &error) as? NSDictionary;

    //println("did read data: \(NSString(data: mutableData, encoding: NSUTF8StringEncoding))")

    if(sock == socketRead){

        if(jsonDic != nil){
            serverSentMessage(jsonDic!)
        }

        self.socketRead?.readDataToData(self.dataDelimiter, withTimeout: -1, tag: 0) //continue reading data
    }
    //have other sockets that only need to read once ever so dont do anything for those
}