首先导入 CocoaAsyncSocket 框架的 GCDAsyncSocket 类
实现聊天需要先开启服务器端,具体参考 :《10086的服务端 - CocoaAsyncSocket 》http://user.qzone.qq.com/153018865/blog/1477541770
#import "ViewController.h"
#import "GCDAsyncSocket.h"
@interface ViewController ()<UITableViewDataSource,GCDAsyncSocketDelegate>
@property (weak, nonatomic) IBOutlet UITextField *textField;
- (IBAction)clickAction:(id)sender;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
/** */
@property (nonatomic,strong) GCDAsyncSocket *clientSocket;
/** 数据源 */
@property (nonatomic,strong) NSMutableArray *dataArr;
@end
@implementation ViewController
- (NSMutableArray *)dataArr
{
if (!_dataArr) {
_dataArr = [NSMutableArray array];
}
return _dataArr;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// 实现聊天室
//1. 连接到群聊服务器
//1.1 创建客户端socket对象
GCDAsyncSocket *clientSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(0, 0)];
self.clientSocket = clientSocket;
//1.2 发送连接请求
NSError *error = nil;
[clientSocket connectToHost:@"192.168.0.98" onPort:5288 error:&error];
if (!error) {
}
//2. 发送聊天消息和接收聊天消息
}
#pragma mark - 与服务器连接成功
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
NSLog(@"与服务器连接成功");
// 监听 读取数据
[sock readDataWithTimeout:-1 tag:0];
}
#pragma mark - 断开连接
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
NSLog(@"断开连接 : %@",err);
}
- (IBAction)clickAction:(id)sender
{
NSString *str = self.textField.text;
if (str.length == 0) {// 无数据
return;
}
//把 数据添加到数据源
[self.dataArr addObject:str];
//刷新表格
[self.tableView reloadData];
// 发送数据
[self.clientSocket writeData:[str dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
}
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (str) {
//把消息添加到数据源
[self.dataArr addObject:str];
// 刷新表格
//放在主线程
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[self.tableView reloadData];
}];
}
// 监听 读取数据
[sock readDataWithTimeout:-1 tag:0];
}
#pragma mark - 表格数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *str = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
cell.textLabel.text = self.dataArr[indexPath.row];
return cell;
}
@end
转载于:https://my.oschina.net/gwlCode/blog/809131