美文网首页
通过socket.io-client-swift实现长连接收发信

通过socket.io-client-swift实现长连接收发信

作者: Mr_Watson | 来源:发表于2018-04-17 11:20 被阅读0次

    库地址:https://github.com/socketio/socket.io-client-swift

    OC版:

    @import SocketIO;
    
    @property (nonatomic, strong) SocketIOClient *socket;
    
    @property (nonatomic, copy) NSString *mySendString;//发送内容 
    @property (nonatomic, copy) NSString *myLoginName;//发送方
    @property (nonatomic, copy) NSString *receiverName;//接收方
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        [self connectSocket];
    }
    
    /**
     连接Socket
     */
    - (void)connectSocket {
        NSURL* url = [[NSURL alloc] initWithString:@"http://localhost:8080"];//仅举例,写自己项目的接口
        SocketManager* manager = [[SocketManager alloc] initWithSocketURL:url config:@{@"log": @YES, @"compress": @YES}];
        SocketIOClient* socket = manager.defaultSocket;    
    
        //监听连接Socket连接是否成功
        [socket on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) {
            NSLog(@"socket connected==%@",data);
        }];
        
        //chat message2 为 监听接收消息 的方法名(为举例)  与后台协定方法名 
        [socket on:@"chat message2" callback:^(NSArray* data, SocketAckEmitter* ack) {
            [self receiveMessage: data];
            NSLog(@"接收到了:%@", data);
        }];
        
        self.socket = socket;
        
        [socket connect];
    }
    
    /**
     发送消息
     @param text 发送内容
     */
    - (void)sendMessage:(NSString *)text {
        NSLog(@"发送消息");
        //发送消息,包括发送方、接收方、发送内容
        //例如:
        NSString *cur = [NSString stringWithFormat:@"%@?%%?%%%@*%%*%%%@",receiverName,text,myLoginName];
    
        mySendString = cur;
        
        //发送消息socket   
        //chat message 为发送消息给后台的方法名 (为举例)  与后台协定方法名
        [self.socket emit:@"chat message" with:@[cur]];
    }
    
    /**
     接收到消息
     
     @param data 消息内容
     */
    - (void)receiveMessage:(NSArray *)data {
     
        NSString *receiveStr = data[0];
        
        if (![mySendString isEqualToString:receiveStr]) {
            
            NSString *str = data[0];
            NSArray *array = [str componentsSeparatedByString:@"?%?%"];
            
            NSString *str1 = array[1];
            NSArray *array1 = [str1 componentsSeparatedByString:@"*%*%"];
            
            if ([array[0] isEqualToString:_loginName]) {
                //消息添加并展示
            }
            NSLog(@"内容内容:%@",array1[0]);
        }else {
            NSLog(@"自己发送的消息,不用处理");
        }
        
        NSLog(@"全部内容:%@, %@",data[0], data);
    }
    

    swift版:

    import SocketIO
    
    var socket: SocketIOClient?
    
    //发送内容 
    var mySendString = ""
    //发送方
    var myLoginName = ""
    //接收方
    var receiverName = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        connectSocket()
    }
    
    /**
     连接Socket
     */
    private func connectSocket() {
        let url = URL(string: "http://localhost:8080") //仅举例,写自己项目的接口
        let manager = SocketManager(socketURL: url, config: ["log": true, "compress": true])
        let socket: SocketIOClient? = manager.defaultSocket
        //监听连接Socket连接是否成功
        socket?.on("connect", callback: {(_ data: [Any]?, _ ack: SocketAckEmitter?) -> Void in
            print("socket connected==\(data ?? "")")
        })
        //chat message2 为 监听接收消息 的方法名(为举例)  与后台协定方法名  
        socket?.on("chat message2", callback: {(_ data: [Any]?, _ ack: SocketAckEmitter?) -> Void in
            self.receiveMessage(data)
            print("接收到了:\(data ?? "")")
        })
        self.socket = socket
        socket?.connect()
    }
    
    /**
     发送消息
     @param text 发送内容
     */
    private func sendMessage(_ text: String?) {
        print("发送消息")
            //发送消息,包括发送方、接收方、发送内容
            //例如:
        let cur = "\(receiverName)?%%?%%\(text ?? "")*%%*%%\(myLoginName)"
        mySendString = cur
        //发送消息socket
        //chat message 为发送消息给后台的方法名 (为举例)  与后台协定方法名
        socket.emit("chat message", with: [cur])
    }
    
    /**
     接收到消息
     @param data 消息内容
     */
    private func receiveMessage(_ data: [Any]?) {
        let receiveStr = data[0] as? String
        if !(mySendString == receiveStr) {
            let str = data[0] as? String
            let array = str?.components(separatedBy: "?%?%")
            let str1 = array[1]
            let array1 = str1.components(separatedBy: "*%*%")
            if (array[0] == loginName) {
                //消息添加并展示
            }
            print("内容内容:\(array1[0])")
        } else {
            print("自己发送的消息,不用处理")
        }
        print("全部内容:\(data[0]), \(data ?? "")")
    }
    
    

    PS:
    由于socket.io-client-swift为swift库,如果项目是用OC语言开发的,需进行桥接才能使用
    参考:iOS混编

    相关文章

      网友评论

          本文标题:通过socket.io-client-swift实现长连接收发信

          本文链接:https://www.haomeiwen.com/subject/crdukftx.html