[XMPP]简易的聊天室实现[二](使用CocoaAsyncSocket)

本文详细介绍了简易聊天室的实现过程,并引入CocoaAsyncSocket框架简化服务器连接部分。通过代理方法实现代理功能,包括数据发送与接收逻辑。文章最后提供了源码链接,供读者参考。

昨天学习了简易聊天室的实现,今天进行继续,使用一个第三方框架CocoaAsyncSocket

http://www.cnblogs.com/hanjian/p/4359568.html

 

连接服务器部分就变的简单多了

- (IBAction)connentToHost:(UIBarButtonItem *)sender

{

    NSString *host = @"10.82.197.21";

    int port = 12345;

    

    //创建一个socket对象

    _asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];

    //连接

    NSError *error;

    [_asyncSocket connectToHost:host onPort:port error:&error];

    if (error) {

        NSLog(@"%@",error);

    }

} 

实现代理方法GCDAsyncSocketDelegate

 #pragma mark - asyncSocket delegate

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port

{

    NSLog(@"连接主机成功");

}


- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err

{

    if (err) {

        NSLog(@"与主机断开连接:%@",err);

    }

}

这里要注意发送数据到服务器成功后读取返回的数据时要我们手动调用方法实现的 

tag可以很好的判断服务器返回的数据对应哪条发送道数据 

#pragma mark 数据成功发送到服务器

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag

{

    NSLog(@"数据成功发送到服务器");

    [_asyncSocket readDataWithTimeout:-1 tag:tag];

}


#pragma mark 服务器有数据返回

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag

{

    NSString *recerveStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    if (tag != 101) {

        [self reloadData:recerveStr];

    }

    NSLog(@"%@",recerveStr);

}

 由于我们给asyncSocket分配了子线程,刷新表格的时候要回到主线程

- (void)reloadData:(NSString *)text

{

    dispatch_async(dispatch_get_main_queue(), ^{

        [self.chatMessages addObject:text];

        [self.tableVIew reloadData];

        //数据多应该往上滚

        NSIndexPath *path = [NSIndexPath indexPathForItem:self.chatMessages.count - 1 inSection:0];

        [self.tableVIew scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:YES];

    });

    

} 

 

文章最后同样附上源码地址:

https://github.com/hjandyz/XMPP 

转载于:https://www.cnblogs.com/hanjian/p/4365386.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值