ios--socket
一、打开服务器
a、在终端打开,到服务器文件路径输入命令 python chatserver.py
b、当显示 Iphone Chat server started 表示成功
二、建立连接
a、设置对应的流
@interface ViewController ()<NSStreamDelegate,UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>{
NSInputStream *_inputStream;//对应输入流
NSOutputStream *_outputStream;//对应输出流
}
b、建立连接
NSString *host = @"127.0.0.1";
int port = 12345;
c、 定义C语言输入输出流
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port, &readStream, &writeStream);
// 把C语言的输入输出流转化成OC对象
_inputStream = (__bridge NSInputStream *)(readStream);
_outputStream = (__bridge NSOutputStream *)(writeStream);
d、 设置代理
_inputStream.delegate = self;
_outputStream.delegate = self;
e、把输入输入流添加到主运行循环; 不添加主运行循环 代理有可能不工作
[_inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[_outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
g、打开输入输出流
[_inputStream open];
[_outputStream open];
}
h、设置代理
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{
NSLog(@"%@",[NSThread currentThread]);
// NSStreamEventOpenCompleted = 1UL << 0,//输入输出流打开完成
// NSStreamEventHasBytesAvailable = 1UL << 1,//有字节可读
// NSStreamEventHasSpaceAvailable = 1UL << 2,//可以发放字节
// NSStreamEventErrorOccurred = 1UL << 3,// 连接出现错误
// NSStreamEventEndEncountered = 1UL << 4// 连接结束
switch (eventCode) {
case NSStreamEventOpenCompleted:
NSLog(@"输入输出流打开完成");
break;
case NSStreamEventHasBytesAvailable:
NSLog(@"有字节可读");
[self readData];
break;
case NSStreamEventHasSpaceAvailable:
NSLog(@"可以发送字节");
break;
case NSStreamEventErrorOccurred:
NSLog(@" 连接出现错误");
break;
case NSStreamEventEndEncountered:
NSLog(@"连接结束");
// 关闭输入输出流
[_inputStream close];
[_outputStream close];
// 从主运行循环移除
[_inputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[_outputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
break;
default:
break;
}
}
-(void)readData{
//建立一个缓冲区 可以放1024个字节
uint8_t buf[1024];
// 返回实际装的字节数
NSInteger len = [_inputStream read:buf maxLength:sizeof(buf)];
// 把字节数组转化成字符串
NSData *data = [NSData dataWithBytes:buf length:len];
// 从服务器接收到的数据
NSString *recStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",recStr);
[self reloadDataWithText:recStr];
}
NSString *text = textField.text;
NSLog(@"%@",text);
// 聊天信息
NSString *msgStr = [NSString stringWithFormat:@"msg:%@",text];
//把Str转成NSData
NSData *data = [msgStr dataUsingEncoding:NSUTF8StringEncoding];
// 刷新表格
[self reloadDataWithText:msgStr];
// 发送数据
[_outputStream write:data.bytes maxLength:data.length];
// 发送完数据,清空textField
textField.text = nil;
return YES;
}