【问题标题】:Cocoaasyncsocket multiple write operationsCocoaasyncsocket 多写操作
【发布时间】:2013-11-13 06:35:58
【问题描述】:

我已经在我的应用程序中实现了 gcdasynsocket 并执行了多个写入操作。委托 didWriteDataWithTag 被调用了两次,但 didreaddata 只被调用了一次(即),仅用于一次写入操作。

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

我不确定出了什么问题。请帮我解决问题

【问题讨论】:

  • 改变这个 [asyncSocket readDataWithTimeout:-1 tag:1000];到 [sock readDataWithTimeout:-1 tag:1000];

标签: ios sockets gcdasyncsocket cocoaasyncsocket


【解决方案1】:

我认为您被 TCP 协议的内部工作原理绊倒了。 TCP 是基于流的协议,而不是基于消息的协议。换句话说,它保证字节将按照它们发送的完全相同的顺序到达,但不能保证这些字节将如何分组到数据包或读取操作中。

具体来说,我怀疑您的两次写入在发送器或接收器中被聚合为一次读取。换句话说,这种行为是完全正常的,也是意料之中的。

您需要使用其他方式将数据分成逻辑单元,而不是依靠每次写入导致接收器中的一次读取。一种常见的技术是用长度字段开始每条消息,这样接收者不仅可以读取每条消息,还可以知道它有多长,并能够找到下一条消息的开始位置。

这里有一个很好的解释:Proper technique for sending multiple pieces of data of arbitrary length over TCP socket

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多