没有调用GCDAsynSocketDelegate didReadData方法.使用GCDAsynSocket



我正试图简单地发送和接收使用GCDAsyncSocket的消息,不能让它工作。

我正在成功地建立连接并写入消息,但是当涉及到读取时,我的委托从未被调用。

我正在使用ios5和这个设置:

客户:

-(void) connectToHost:(HostAddress*)host{
    NSLog(@"Trying to connect to host %@", host.hostname);
    if (asyncSocket == nil)
    {
        asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
        NSError *err = nil;
        if ([asyncSocket connectToHost:host.hostname onPort:host.port error:&err])
        {
            NSLog(@"Connected to %@", host.hostname);
            NSString *welcomMessage = @"Hello from the clientrn";
            [asyncSocket writeData:[welcomMessage dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:1];
            [asyncSocket readDataWithTimeout:-1 tag:0];
        }else
            NSLog(@"%@", err);
    }
}

Delegate didReadData方法未被调用

-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    NSLog(@"MESSAGE: %@", [NSString stringWithUTF8String:[data bytes]]);
}
服务器

-(void)viewDidLoad{
    asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    connectedSockets = [[NSMutableArray alloc] init];
    NSError *err = nil;
    if ([asyncSocket acceptOnPort:0 error:&err]){
        UInt16 port = [asyncSocket localPort];
        //...bojour stuff
    }
    else{
        NSLog(@"Error in acceptOnPort:error: -> %@", err);
    }
}

写一个消息给客户端,等待socket连接成功后的响应

- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
    NSLog(@"Accepted new socket from %@:%hu", [newSocket connectedHost], [newSocket connectedPort]);
    // The newSocket automatically inherits its delegate & delegateQueue from its parent.
    [connectedSockets addObject:newSocket];
    NSString *welcomMessage = @"Hello from the serverrn";
    [asyncSocket writeData:[welcomMessage dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:1];
    [asyncSocket readDataWithTimeout:-1 tag:0];
}

这个不叫…

-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    NSLog(@"New message from client... ");
}

好的,找到答案了。

问题是我在自己的套接字端而不是在连接的套接字端读写。

修复:(将asyncSocket改为newSocket)

- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
    NSLog(@"Accepted new socket from %@:%hu", [newSocket connectedHost], [newSocket connectedPort]);
    // The newSocket automatically inherits its delegate & delegateQueue from its parent.
    [connectedSockets addObject:newSocket];
    NSString *welcomMessage = @"Hello from the serverrn";
    [newSocket writeData:[welcomMessage dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:1];
    [newSocket readDataWithTimeout:-1 tag:0];
}

最新更新