[XMPP]简易的聊天室实现[二](使用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 

posted @ 2015-03-25 12:59  罕见  阅读(299)  评论(0编辑  收藏  举报