I am trying to just send and receive a message using GCDAsyncSocket and cannot make it work.
I successfully establish a connection and write messages, but when it comes to reading, my delegate is never called.
I am using ios5 and this setting:
Client:
-(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 client\r\n"; [asyncSocket writeData:[welcomMessage dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:1]; [asyncSocket readDataWithTimeout:-1 tag:0]; }else NSLog(@"%@", err); } }
The delegated method didReadData is not called
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{ NSLog(@"MESSAGE: %@", [NSString stringWithUTF8String:[data bytes]]); }
Server
-(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];
Write a message to the client and wait for a response to a successful socket connection
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket { NSLog(@"Accepted new socket from %@:%hu", [newSocket connectedHost], [newSocket connectedPort]);
And this is not called ever ...
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{ NSLog(@"New message from client... "); }
source share