我试图简单地使用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... ");
}
答案 0 :(得分:3)
好的,找到了答案。
问题是我在自己的套接字端而不是连接的套接字上写和读。
修正:(将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 server\r\n";
[newSocket writeData:[welcomMessage dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:1];
[newSocket readDataWithTimeout:-1 tag:0];
}