iOS之NSStream聊天室

Swift

//
//  ViewController.swift
//  stocket
//
//  Created by ling on 16/1/4.
//  Copyright © 2016年 ling. All rights reserved.
//

import UIKit

class ViewController: UIViewController,NSStreamDelegate {
    
    
    var inputStream:NSInputStream?
    var outputSteam:NSOutputStream?
    
    var incomingDataBuffer =  NSMutableData()
    var outgoingDataBuffer =  NSMutableData()
    

    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    
    //一、代理方法
    func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
     //   print("%@",NSThread.currentThread())
        
        switch eventCode {
        
        case  NSStreamEvent.OpenCompleted:
            print("输入输出流打开完成")
        case  NSStreamEvent.HasBytesAvailable:
            print("有字节可读")
            self.readData()
        case  NSStreamEvent.HasSpaceAvailable:
            print("可以发送字节")
        case  NSStreamEvent.ErrorOccurred:
            print("连接出现错误")
        case  NSStreamEvent.EndEncountered:
            print("连接结束")
        
            //关闭输入输出流
            inputStream?.close()
            outputSteam?.close()
            
            //从主运行循环移除
            inputStream?.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
            outputSteam?.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
            
        default:
            break
        
    }
        
    }
    
    //二、链接服务器
    @IBAction func linkBtn(sender: UIButton) {
        
        //1.建立连接
        let host:CFString = "127.0.0.1"
        let port:UInt32 = 8004
        
        //定义C语言输入输出流
        var readStream:  Unmanaged<CFReadStream>?
        var writeStream: Unmanaged<CFWriteStream>?
        
        CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault,host, port, &readStream, &writeStream);
        
        //把C语言的输入输出流转换成swift对象
        self.inputStream = readStream!.takeUnretainedValue()
        self.outputSteam = writeStream?.takeUnretainedValue()
        
        //设置代理
        self.inputStream?.delegate = self
        self.outputSteam?.delegate = self
        
        //把输入输出流添加到主循环
        self.inputStream?.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
        self.outputSteam?.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
        
        //打开输入输出流
        self.inputStream?.open()
        self.outputSteam?.open()
        
    }
    
    //三、登录
    @IBAction func loginBtn(sender: UIButton) {
        
        //登录指令
        let loginStr = "iam:ling"
        
        //Str转成NSData
        let data = loginStr.dataUsingEncoding(NSUTF8StringEncoding)
        
        //NSData转为NSMutableData
        self.outgoingDataBuffer.appendData(data!)

        let readBytes = self.outgoingDataBuffer.mutableBytes
        
        let len = self.outgoingDataBuffer.length

        let buf = UnsafeMutablePointer<UInt8>.alloc(len)
        memcpy(buf, readBytes, len)
        
        self.outputSteam?.write(buf, maxLength: len)
    }
    
    //四、读取服务器返回数据
    let maxBuff = 1024
    func readData(){
        
        //建立一个缓冲区,可以放1024个字节
        let buf = UnsafeMutablePointer<UInt8>.alloc(maxBuff)
      
        //返回实际装的字节数
        let len = self.inputStream!.read(buf, maxLength: maxBuff)
        
        //把字节数组转化成字符串
        let data = NSData(bytes: buf, length: len)
        
        //从服务器接收到的数据
        let recStr = NSString.init(data: data, encoding: NSUTF8StringEncoding)
        
        print(recStr)
    }
    
    
    }


Objective-C

//
//  ViewController.m
//  StocketAndOC
//
//  Created by ling on 16/1/5.
//  Copyright © 2016年 ling. All rights reserved.
//

#import "ViewController.h"

@interface ViewController () <NSStreamDelegate>{
    NSInputStream *_inputStream;
    NSOutputStream *_outputStream;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

//1.代理方法
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
    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;
    }
}

- (IBAction)linkBtn:(UIButton *)sender {
    
    // 1.建立连接
    NSString *host = @"127.0.0.1";
    int port = 8004;
    
    // 定义C语言输入输出流
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port, &readStream, &writeStream);
    
    // 把C语言的输入输出流转化成OC对象
    _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];

}


- (IBAction)loginBtn:(UIButton *)sender {
    
    //登录的指令
    NSString *loginStr = @"iam:zhangsan";
    
    //把Str转成NSData
    NSData *data = [loginStr dataUsingEncoding:NSUTF8StringEncoding];
    
    
    [_outputStream write:data.bytes maxLength:data.length];
}

#pragma mark 读了服务器返回的数据
-(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);

    
}
@end


你可能感兴趣的:(iOS之NSStream聊天室)