Ios Cocoaasyncsocket多个写入操作
我已经在我的应用程序中实现了gcdasynsocket并执行了多个写入操作。委托didWriteDataWithTag被调用两次,而didreaddata只被调用一次(ie),用于一次写入操作Ios Cocoaasyncsocket多个写入操作,ios,sockets,gcdasyncsocket,cocoaasyncsocket,Ios,Sockets,Gcdasyncsocket,Cocoaasyncsocket,我已经在我的应用程序中实现了gcdasynsocket并执行了多个写入操作。委托didWriteDataWithTag被调用两次,而didreaddata只被调用一次(ie),用于一次写入操作 -(void)connectToHost:(NSString*)ip andPort:(NSString*)port { if(![asyncSocket isConnected]) { dispatch_queue_t mainQueue = dispatch_get_m
-(void)connectToHost:(NSString*)ip andPort:(NSString*)port
{
if(![asyncSocket isConnected])
{
dispatch_queue_t mainQueue = dispatch_get_main_queue();
asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:mainQueue];
NSError *error = nil;
uint16_t portNumber = (uint16_t)[port integerValue];
if (![asyncSocket connectToHost:ip onPort:portNumber withTimeout:-1 error:&error])
{
NSLog(@"Error connecting: %@", error);
}
else
{
NSLog(@"Connecting...");
}
}}
GCDasyncsocket委托方法
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
NSLog(@"connected to host");
[asyncSocket writeData:dataToBeWritten1 withTimeout:-1 tag:1000];
[asyncSocket writeData:dataToBeWritten2 withTimeout:-1 tag:2000];
}
-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
[asyncSocket readDataWithTimeout:-1 tag:tag];
}
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
if (tag==1000)
{
NSLog(@"didReadData and tag-----%@-----%ld",data,tag);
[asyncSocket readDataWithTimeout:-1 tag:2000];
}
else if(tag==2000)
{
NSLog(@"didReadData and tag-----%@-----%ld",data,tag);
[asyncSocket readDataWithTimeout:-1 tag:1000];
}
}
我不确定出了什么问题。请帮我解决这个问题我想你被TCP协议的内部工作绊倒了。TCP是基于流的协议,而不是基于消息的协议。换句话说,它保证字节将以与发送完全相同的顺序到达,但无法保证这些字节将如何分组到数据包或读取操作中 具体地说,我怀疑您的两次写入(在发射机或接收机中)正在聚合为一次读取。换句话说,这种行为是完全正常的,也是意料之中的 除了依赖每次写入导致接收器中只有一次读取之外,还需要使用其他方法将数据分离为逻辑单元。一种常见的技术是使用长度字段开始每条消息,该字段不仅允许接收者读取每条消息,还允许接收者知道消息的长度,并能够找到下一条消息的起始位置
这里有一个很好的解释来说明如何执行此操作:更改此[asyncSocket readDataWithTimeout:-1标记:1000];至[sock readDataWithTimeout:-1标记:1000];