AsyncSocket 使用

  今天使用AsyncSocket模拟及时通信,在这里记录一下,免得以后自己又犯相同的错误

  1>创建客户端和服务器socket

 /**
* 设置socket
*/
- (void)setupSocket
{
//1.客户端socket
_clientSocket = [[AsyncSocket alloc] initWithDelegate:self];
//2. 启用定时器连接服务器 [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(tryToConnect:) userInfo:nil repeats:YES]; //3.实例化服务器
_serverSocket = [[AsyncSocket alloc] initWithDelegate:self]; [_serverSocket acceptOnPort: error:nil];
}

  定时器代码:

 - (void)tryToConnect:(NSTimer *)timer
{
if ([_clientSocket isConnected]) {
[timer invalidate];
return;
}
NSString *host = @"10.0.185.132";
UInt16 port = ;
[_clientSocket connectToHost:host onPort:port withTimeout:- error:nil];
}

  2>实现协议回调方法

 #pragma mark - socket协议

 - (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket
{
NSLog(@"接收到新的socket连接");
[_connectArray addObject:newSocket];
[newSocket readDataWithTimeout:- tag:];
}
/*
* 客户端连接服务器失败时的回调
*/
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
NSLog(@"客户端连接失败,错误信息:%@", [err localizedDescription]);
} /*
* 客户端连接服务器成功时的回调
*/
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(@"客户端连接成功:host:%@ port :%d", host, port);
} //接收客户端发送过来的数据 - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSString *message =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; [self sendMessage:message messageType:MessageTypeOther]; //特别注意这句话一定要写,不然只会读取第一条数据,写这句话表示不停的等待读取数据
[sock readDataWithTimeout:- tag:];
}

  3>发送信息

 NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];

     //发送消息
if ([_clientSocket isConnected]) {
[_clientSocket writeData:data withTimeout: tag:]; }else{
NSLog(@"连接断开");
//尝试重新连接
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(tryToConnect:) userInfo:nil repeats:YES];
}
上一篇:ViewPager实现广告自动轮播核心代码(Handler+Thread)


下一篇:学问Chat UI(3)