其他分享
首页 > 其他分享> > AsyncSocket 使用

AsyncSocket 使用

作者:互联网

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

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

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

  定时器代码:

 1 - (void)tryToConnect:(NSTimer *)timer
 2 {
 3     if ([_clientSocket isConnected]) {
 4         [timer invalidate];
 5         return;
 6     }
 7     NSString *host = @"10.0.185.132";
 8     UInt16 port = 8080;
 9     [_clientSocket connectToHost:host onPort:port withTimeout:-1 error:nil];
10 }

  2>实现协议回调方法

 1 #pragma mark - socket协议
 2 
 3 - (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket
 4 {
 5     NSLog(@"接收到新的socket连接");
 6     [_connectArray addObject:newSocket];
 7     [newSocket readDataWithTimeout:-1 tag:300];
 8 }
 9 /*
10  * 客户端连接服务器失败时的回调
11  */
12 - (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
13 {
14     NSLog(@"客户端连接失败,错误信息:%@", [err localizedDescription]);
15 }
16 
17 /*
18  * 客户端连接服务器成功时的回调
19  */
20 - (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
21 {
22     NSLog(@"客户端连接成功:host:%@ port :%d", host, port);
23 }
24 
25 //接收客户端发送过来的数据
26 
27 - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
28 {
29     NSString *message =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
30 
31     [self sendMessage:message messageType:MessageTypeOther];
32     
33     //特别注意这句话一定要写,不然只会读取第一条数据,写这句话表示不停的等待读取数据
34     [sock readDataWithTimeout:-1 tag:300];
35 }

  3>发送信息

 1 NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
 2     
 3     //发送消息
 4     if ([_clientSocket isConnected]) {
 5         [_clientSocket writeData:data withTimeout:60 tag:100];
 6         
 7     }else{
 8         NSLog(@"连接断开");
 9         //尝试重新连接
10         [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(tryToConnect:) userInfo:nil repeats:YES];
11     }

 

转载于:https://www.cnblogs.com/pretty-guy/p/4119779.html

标签:socket,void,host,使用,AsyncSocket,port,客户端
来源: https://blog.csdn.net/weixin_34409822/article/details/94287738