Cyp*_*ian 6 iphone objective-c ios5 cocoaasyncsocket gcdasyncsocket
我试图简单地使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
不调用Delegate didReadData方法
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
NSLog(@"MESSAGE: %@", [NSString stringWithUTF8String:[data bytes]]);
}
Run Code Online (Sandbox Code Playgroud)
服务器
-(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);
}
}
Run Code Online (Sandbox Code Playgroud)
向客户端写入消息并等待成功套接字连接的响应
- (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];
}
Run Code Online (Sandbox Code Playgroud)
这不是永远的称呼......
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
NSLog(@"New message from client... ");
}
Run Code Online (Sandbox Code Playgroud)
好的,找到答案了。
问题是我在自己的套接字端而不是连接的套接字上写入和读取。
修正:(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];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4868 次 |
| 最近记录: |