//ios这里实现socket的链接,使C语言
//1.与服务器通过三次握手实现链接
NSString *host = @"127.0.0.1";
int port = 54321;
CFReadStreamRef readStream; CFWriteStreamRef writeStream;
//3.分配输入输出流的内存空间CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host,port,&readStream, &writeStream);
//4.把C语言的输入输出流转成OC对象
_inputStream = (__bridge NSInputStream *)(readStream);
_outputStream = (__bridge NSOutputStream *)(writeStream);
//5.设置代理,监听数据接收的状态
_outputStream.delegate = self;
_inputStream.delegate = self;
[_outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[_inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
//6打开输入输出流
[_inputStream open];
[_outputStream open];
#pragma mark--- NSStreamDelegate
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{
switch (eventCode) {
case NSStreamEventOpenCompleted:
NSLog(@"成功建立链接,形成输入输出流的传输通道");
break;
case NSStreamEventHasBytesAvailable:
NSLog(@"有数据可读");
[self readData];
break;case NSStreamEventHasSpaceAvailable:NSLog(@"可以发送数据");break;case NSStreamEventEndEncountered:NSLog(@"正常的断开链接");//断开连接时,把输入输出流关闭,而且还要从主运行循环中移除[_inputStream close];[_outputStream close];[_inputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];[_outputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];break;default:break;}
网友评论