gpt4 book ai didi

iOS:GCDAsyncSocket 及其标签

转载 作者:行者123 更新时间:2023-11-29 02:48:33 24 4
gpt4 key购买 nike

在我的应用程序中,我使用 GCDAsyncSocket,并以这种方式写入和读取:

NSData *bufferWriteData = [NSData dataWithBytesNoCopy:bufferWrite length:17 freeWhenDone:YES];
[self.socket writeData:bufferWriteData withTimeout:-1 tag:1];
[self.socket readDataWithTimeout:-1 tag:1];

在我读取委托(delegate)方法中的数据后:

- (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];
}

在这个委托(delegate)方法中,我记得“readDataWithTimeout”,所以通过这种方式我读取了所有数据。

当我进行新调用时的问题 ID(如果我这样做):

[self.socket writeData:bufferWriteData withTimeout:-1 tag:2];
[self.socket readDataWithTimeout:-1 tag:2];

我使用 tag = 2 开始新的写入和新的读取;当调用委托(delegate)方法“didReadData”时,我的代码进入 tag = 1; block 内它似乎无法识别新标签。

为什么会这样?

最佳答案

有几种方法可以处理这个问题。在您的情况下,最好的方法可能只是使用终止符来指示该数据段的结尾。你可以在那里阅读: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
}

关于iOS:GCDAsyncSocket 及其标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24810076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com