首页 技术 正文
技术 2022年11月14日
0 收藏 628 点赞 2,967 浏览 1830 个字

@import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
@import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);

昨天学习了简易聊天室的实现,今天进行继续,使用一个第三方框架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

上一篇: js280行代码写2048
下一篇: CCPC final Cockroaches
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,941
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,465
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,280
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,094
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,728
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,765