在我的应用程序中,我正在使用GCDAsyncSocket,我以这种方式编写和阅读:
NSData *bufferWriteData = [NSData dataWithBytesNoCopy:bufferWrite length:17 freeWhenDone:YES];
[self.socket writeData:bufferWriteData withTimeout:-1 tag:1];
[self.socket readDataWithTimeout:-1 tag:1];
在我读取委托方法后的数据:
- (void) socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
NSLog(@"did read data");
if (tag == 1){
//analyze my data...
[self.socket readDataWithTimeout:-1 tag:1];
}
在这个委托方法中我记得“readDataWithTimeout”所以这样我就读了所有数据。
如果我这样做,那么当我拨打新电话时会出现问题:
[self.socket writeData:bufferWriteData withTimeout:-1 tag:2];
[self.socket readDataWithTimeout:-1 tag:2];
我开始一个新的写入和一个标签= 2的新读取; 当委托方法“didReadData”被调用时,我的代码在tag = 1的块内输入;它似乎无法识别新标签。
为什么会这样?
答案 0 :(得分:1)
有几种方法可以解决这个问题。在您的情况下,最好的方法可能只是使用终结符来指示该数据段的结束。你可以在那里阅读:TCP is a stream.
NSData *MyCommandTerminator(void)
{
return [NSData dataWithBytes:"\x0D\x0A\x0B\x0A" length:4];
}
//callback from Asyncsocket for incoming data
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag //sender and receiver
{
NSLog(@"GCDAsyncSocket didreaddata");
// do what you wish with data and read again using a terminator
[sock readDataToData:MyCommandTerminator() withTimeout:-1 tag:1]; //tag is not being used here
}
// your method to send data
-(void)sendData:(NSData *)data
{
// NSData *bufferWriteData = [NSData dataWithBytesNoCopy:bufferWrite length:17 freeWhenDone:YES];
NSLog(@"Sendata wehere _peerSocket is your instance of GCDAsyncSocket");
NSMutableData *myData = [[NSMutableData alloc] initWithData:data];
[myData appendData:MyCommandTerminator()];
[_peerSocket writeData:myData withTimeout:-1 tag:2]; // tag is not being used here
}