我正在尝试使用 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 client\r\n";
[asyncSocket writeData:[welcomMessage dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:1];
[asyncSocket readDataWithTimeout:-1 tag:0];
}else
NSLog(@"%@", err);
}
}
未调用委托 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);
}
}
向客户端写入消息并等待套接字连接成功的响应
- (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 server\r\n";
[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... ");
}