iOS 客户端Socket

头文件

#import 

@interface ViewController : UIViewController  {
    NSInputStream  *_inputStream;
    NSOutputStream *_outputStream;
}

@property (strong, nonatomic) NSMutableArray *messages;

@end

实现文件

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self connectToServer];
}

#pragma mark - event response

- (void)connectToServer {
    
    NSString *host = @"towel.blinkenlights.nl";
    
    int port = 23;
    
    CFReadStreamRef  readStream;
    CFWriteStreamRef writeStream;
    
    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port,&readStream, &writeStream);
    
    _inputStream  = (__bridge NSInputStream *)(readStream);
    _outputStream = (__bridge NSOutputStream *)(writeStream);
    
    _inputStream.delegate  = self;
    _outputStream.delegate = self;
    
    [_inputStream  scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [_outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    
    [_inputStream open];
    [_outputStream open];
}


#pragma mark - NSStreamDelegate

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {
    
    NSLog(@"%@",[NSThread currentThread]);
    
    switch (eventCode) {
        case NSStreamEventNone: {
            
            break;
        }
        case NSStreamEventOpenCompleted: {
            NSLog(@"输入输入流打开完成");
            break;
        }
        case NSStreamEventHasBytesAvailable: {
            NSLog(@"有字节可读");
            
            [self readStream];
            
            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;
        }
    }
}

#pragma private method

- (void)readStream {
    
    uint8_t buff[1024];
    
    NSUInteger len = [_inputStream read:buff maxLength:sizeof(buff)];
    
    NSData *data = [NSData dataWithBytes:buff length:len];
    
    NSString *recieve = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSLog(@"%@",recieve);
}

#pragma mark - setter & getter

- (NSMutableArray *)messages {
    if (_messages == nil) {
     
        _messages = [NSMutableArray array];
    }
    return _messages;
}

@end

关键函数其实就是

CFStreamCreatePairWithSocketToHost

满足这个函数的参数需求就可以了。

你可能感兴趣的:(iOS 客户端Socket)