GCDAsyncSocket聊天实践

2019-08-01  本文已影响0人  大猿媛

鉴于服务器已经有搭建好的socket服务器,所以我只关注iOS端如何通过CocoaSyncSocket实现客服聊天

创建聊天工具单例KefuHelper,遵守协议GCDAsyncSocketDelegate

-(instancetype)init{
    if (self = [super init]) {
        self.clientSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];     
    }
    return self;
}
-(void)connect{
    NSError *error = nil;
    self.isConnected = [self.clientSocket connectToHost:@"47.94.39.111" onPort:8283 error:&error];
    QMPLog(@"链接socket服务器----%@",error);
}
#pragma mark - GCDAsyncSocketDelegate
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    //    NSLog(@"连接主机对应端口%@", sock);
    [PublicTool showMsg:@"链接成功"];
    QMPLog(@"服务器IP: %@-------端口: %d", host,port);
 
    // 连接成功开启定时器,发送心跳包,用于检测链接是否断开
    [self addTimer];
    // 连接后,可读取服务端的数据
    [self.clientSocket readDataWithTimeout:-1 tag:0];
    self.isConnected = YES;
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    [PublicTool showMsg:@"断开连接"];
    QMPLog(@"服务器链接失败: -----%@", err);
    self.clientSocket.delegate = nil;
    self.clientSocket = nil;
    self.isConnected = NO;
    [self.connectTimer invalidate];
}

// 接收到socket服务器发来的消息,发送消息后端写了相应API, 不通过socket发送
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString *text = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    [PublicTool showMsg:[NSString stringWithFormat:@"socket接收数据--%@",text]];
    // 读取到服务端数据值后,能再次读取
    [self.clientSocket readDataWithTimeout:-1 tag:0];
}
- (void)addTimer{
    self.connectTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(longConnectToSocket) userInfo:nil repeats:YES];
    // 把定时器添加到当前运行循环,并且调为通用模式
    [[NSRunLoop currentRunLoop] addTimer:self.connectTimer forMode:NSRunLoopCommonModes];
}

// 心跳连接
- (void)longConnectToSocket
{
    // 发送固定格式的数据,指令@"longConnect"
    float version = [[UIDevice currentDevice] systemVersion].floatValue;
    NSString *longConnect = [NSString stringWithFormat:@"123%f",version];
    
    NSData  *data = [longConnect dataUsingEncoding:NSUTF8StringEncoding];
    
    [self.clientSocket writeData:data withTimeout:-1 tag:0];
}
GCDAsyncSocket常见问题
- (BOOL)connectToHost:(NSString*)host onPort:(uint16_t)port error:(NSError **)errPtr
{
return [self connectToHost:host onPort:port withTimeout:5 error:errPtr];
}
上一篇下一篇

猜你喜欢

热点阅读