原因出在这个方法:[self.clientSocket readDataWithTimeout:-1 tag:0];
在连接成功的代理中:
//连接成功
-(void)socket:(GCDAsyncSocket*)sockdidConnectToHost:(NSString*)hostport:(uint16_t)port {
NSLog(@"--连接成功--");
//必须加这个方法
[self.clientSocket readDataWithTimeout:-1 tag:0];
}
在收到消息的代理中:
//收到的消息
-(void)socket:(GCDAsyncSocket*)sockdidReadData:(NSData*)datawithTag:(long)tag {//也必须调用这个方法
[self.clientSocket readDataWithTimeout:-1 tag:0];
//数据格式转换
NSString*recvStr;
if(data) {
recvStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
NSLog(@"%@",recvStr);
}
完整的代码
#import <GCDAsyncSocket.h>
@interface MYSocketHelper () < GCDAsyncSocketDelegate>
@property (nonatomic, strong) GCDAsyncSocket *clientSocket;
@end
-(void)asynSocketInit {
self.clientSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(0, 0)];
NSError*err =nil;
if (![self.clientSocket connectToHost:@"127.0.0.1" onPort: 60000 error:&err]) {
NSLog(@"I goofed: %@", err);
} else {
[self.clientSocket writeData:[@"xxxx" dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
}
}
-(void)socket:(GCDAsyncSocket*)sockdidConnectToHost:(NSString*)hostport:(uint16_t)port {
NSLog(@"--连接成功--");
[self.clientSocket readDataWithTimeout:-1 tag:0];
}
-(void)socket:(GCDAsyncSocket*)sockdidReadData:(NSData*)datawithTag:(long)tag {
[self.clientSocket readDataWithTimeout:-1 tag:0];
NSString*recvStr;
if(data) {
recvStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
NSLog(@"%@",recvStr);
}
- (void)socket:(GCDAsyncSocket*)sockdidReadPartialDataOfLength:(NSUInteger)partialLengthtag:(long)tag {
}
-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err {
}
自测的话可以下载一个ssokit,模拟了socket服务端,能收发消息
ssokit界面地址:127.0.0.1本机的地址,端口范围 1024~65535。
网友评论