zoukankan      html  css  js  c++  java
  • iOS websocket接入的简单使用

     

    接触WebSocket

    考虑到普通的HTTP 通信方式只能由客户端主动拉取,服务器不能主动推给客户端 。然后就想出的2种解决方案。

    1.和后台沟通了一下 他们那里使用的是WebSocket ,所以就使用WebSocket让我们app端和服务器建立长连接。这样就可以事实接受他发过来的消息
    2.使用推送,也可以实现接收后台发过来的一些消息

    最后还是选择了WebSocket,找到了facebook的 SocketRocket 框架。下面是接入过程中的一些记录

    WebSocket

    WebSocket 是 HTML5 一种新的协议。它实现了浏览器与服务器全双工通信,能更好的节省服务器资源和带宽并达到实时通讯,它建立在 TCP 之上,同 HTTP 一样通过 TCP 来传输数据,但是它和 HTTP 最大不同是:

    WebSocket 是一种双向通信协议,在建立连接后,WebSocket 服务器和 Browser/Client Agent 都能主动的向对方发送或接收数据,就像 Socket 一样;

    WebSocket 需要类似 TCP 的客户端和服务器端通过握手连接,连接成功后才能相互通信。

    具体在这儿  WebSocket 是什么原理?为什么可以实现持久连接?

    用法

    我使用的是pod管理库 所以在podfile中加入
    pod 'SocketRocket'

    在使用命令行工具cd到当前工程 安装
    pod install

    如果是copy的工程中的 SocketRocket库的github地址:SocketRocket

    导入库到工程中以后首先封装一个SocketRocketUtility单例

    SocketRocketUtility.m文件中的写法如下:

    #import "SocketRocketUtility.h"
    #import <SocketRocket.h>
    
    NSString * const kNeedPayOrderNote = @"kNeedPayOrderNote";//发送的通知名称
    
    @interface SocketRocketUtility()<SRWebSocketDelegate>
    {
        int _index;
        NSTimer * heartBeat;
        NSTimeInterval reConnectTime;
    }
    
    @property (nonatomic,strong) SRWebSocket *socket;
    
    @end
    
    @implementation SocketRocketUtility
    
    + (SocketRocketUtility *)instance {
        static SocketRocketUtility *Instance = nil;
        static dispatch_once_t predicate;
        dispatch_once(&predicate, ^{
            Instance = [[SocketRocketUtility alloc] init];
        });
        return Instance;
    }
    
    //开启连接
    -(void)SRWebSocketOpenWithURLString:(NSString *)urlString {
        if (self.socket) {
            return;
        }
    
        if (!urlString) {
            return;
        }
    
        //SRWebSocketUrlString 就是websocket的地址 写入自己后台的地址
        self.socket = [[SRWebSocket alloc] initWithURLRequest:
                       [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
        
        self.socket.delegate = self;   //SRWebSocketDelegate 协议
        
        [self.socket open];     //开始连接
    }
    
    //关闭连接
    - (void)SRWebSocketClose {
        if (self.socket){
            [self.socket close];
            self.socket = nil;
            //断开连接时销毁心跳
            [self destoryHeartBeat];
        }
    }
    
    #pragma mark - socket delegate
    - (void)webSocketDidOpen:(SRWebSocket *)webSocket {
        NSLog(@"连接成功,可以与服务器交流了,同时需要开启心跳");
        //每次正常连接的时候清零重连时间
        reConnectTime = 0;
        //开启心跳 心跳是发送pong的消息 我这里根据后台的要求发送data给后台
        [self initHeartBeat];
        [[NSNotificationCenter defaultCenter] postNotificationName:kWebSocketDidOpenNote object:nil];
    }
    
    - (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error {
        NSLog(@"连接失败,这里可以实现掉线自动重连,要注意以下几点");
        NSLog(@"1.判断当前网络环境,如果断网了就不要连了,等待网络到来,在发起重连");
        NSLog(@"2.判断调用层是否需要连接,例如用户都没在聊天界面,连接上去浪费流量");
        NSLog(@"3.连接次数限制,如果连接失败了,重试10次左右就可以了,不然就死循环了。)";
        _socket = nil;
        //连接失败就重连
        [self reConnect];
    }
    
    - (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean {
        NSLog(@"被关闭连接,code:%ld,reason:%@,wasClean:%d",code,reason,wasClean);
        //断开连接 同时销毁心跳
        [self SRWebSocketClose];
    }
    
    /*
     该函数是接收服务器发送的pong消息,其中最后一个是接受pong消息的,
     在这里就要提一下心跳包,一般情况下建立长连接都会建立一个心跳包,
     用于每隔一段时间通知一次服务端,客户端还是在线,这个心跳包其实就是一个ping消息,
     我的理解就是建立一个定时器,每隔十秒或者十五秒向服务端发送一个ping消息,这个消息可是是空的
     */
    -(void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload{
    
        NSString *reply = [[NSString alloc] initWithData:pongPayload encoding:NSUTF8StringEncoding];
        NSLog(@"reply===%@",reply);
    }
    
    - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message  {
        //收到服务器发过来的数据 这里的数据可以和后台约定一个格式 我约定的就是一个字符串 收到以后发送通知到外层 根据类型 实现不同的操作
        NSLog(@"%@",message);
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kNeedPayOrderNote object:message];
    }
    
    #pragma mark - methods
    //重连机制
    - (void)reConnect
    {
        [self SRWebSocketClose];
        //超过一分钟就不再重连 所以只会重连5次 2^5 = 64
        if (reConnectTime > 64) {
            return;
        }
      
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(reConnectTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.socket = nil;
            [self SRWebSocketOpen];
            NSLog(@"重连");
        });
        
        //重连时间2的指数级增长
        if (reConnectTime == 0) {
            reConnectTime = 2;
        }else{
            reConnectTime *= 2;
        }
    }
    
    //初始化心跳
    - (void)initHeartBeat
    {
        dispatch_main_async_safe(^{
            [self destoryHeartBeat];
            __weak typeof(self) weakSelf = self;
            //心跳设置为3分钟,NAT超时一般为5分钟
            heartBeat = [NSTimer scheduledTimerWithTimeInterval:3*60 repeats:YES block:^(NSTimer * _Nonnull timer) {
                NSLog(@"heart");
                //和服务端约定好发送什么作为心跳标识,尽可能的减小心跳包大小
                [weakSelf sendData:@"heart"];
            }];
            [[NSRunLoop currentRunLoop]addTimer:heartBeat forMode:NSRunLoopCommonModes];
        })
    }
    
    //取消心跳
    - (void)destoryHeartBeat
    {
        dispatch_main_async_safe(^{
            if (heartBeat) {
                [heartBeat invalidate];
                heartBeat = nil;
            }
        })
    }
    
    //pingPong机制
    - (void)ping{
        [self.socket sendPing:nil];
    }
    
    #define WeakSelf(ws) __weak __typeof(&*self)weakSelf = self
    - (void)sendData:(id)data {
    
        WeakSelf(ws);
        dispatch_queue_t queue =  dispatch_queue_create("zy", NULL);
        
        dispatch_async(queue, ^{
            if (weakSelf.socket != nil) {
                // 只有 SR_OPEN 开启状态才能调 send 方法,不然要崩
                if (weakSelf.socket.readyState == SR_OPEN) {
                    [weakSelf.socket send:data];    // 发送数据
                    
                } else if (weakSelf.socket.readyState == SR_CONNECTING) {
                    NSLog(@"正在连接中,重连后其他方法会去自动同步数据");
                    // 每隔2秒检测一次 socket.readyState 状态,检测 10 次左右
                    // 只要有一次状态是 SR_OPEN 的就调用 [ws.socket send:data] 发送数据
                    // 如果 10 次都还是没连上的,那这个发送请求就丢失了,这种情况是服务器的问题了,小概率的
                    [self reConnect];
                    
                } else if (weakSelf.socket.readyState == SR_CLOSING || weakSelf.socket.readyState == SR_CLOSED) {
                    // websocket 断开了,调用 reConnect 方法重连
                    [self reConnect];
                }
            } else {
                NSLog(@"没网络,发送失败,一旦断网 socket 会被我设置 nil 的");
            }
        });
    }
    
    -(void)dealloc{
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    

    然后在需要开启socket的地方调用
    [[SocketRocketUtility instance] SRWebSocketOpenWithURLString:@"写入自己后台的地址"];
    在需要断开连接的时候调用
    [[SocketRocketUtility instance] SRWebSocketClose];

    使用这个框架最后一个很重要的 需要注意的一点

    这个框架给我们封装的webscoket在调用它的sendPing senddata方法之前,一定要判断当前scoket是否连接,如果不是连接状态,程序则会crash。

    结语

    这里简单的实现了连接和收发数据 后续看项目需求在加上后续的改进 希望能够帮助第一次写的iOSer 。 希望有更好的方法的童鞋可以有进一步的交流 : )

    4月10日 更新:

    /// Creates and returns a new NSTimer object initialized with the specified block object and schedules it on the current run loop in the default mode.
    /// - parameter:  ti    The number of seconds between firings of the timer. If seconds is less than or equal to 0.0, this method chooses the nonnegative value of 0.1 milliseconds instead
    /// - parameter:  repeats  If YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires.
    /// - parameter:  block  The execution body of the timer; the timer itself is passed as the parameter to this block when executed to aid in avoiding cyclical references
    + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
    

    上面发送心跳包的方法是iOS10才可以用的 其他版本会崩溃 要适配版本 要选择 这个方法

    + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
    

    8月10日 更新demo地址

    demo地址
    可以下载下来看看哦 :)

    demo中的后台地址未设置 所以很多同学直接运行就报错了 设置一个自己后台的地址就ok了 :)

     
     
    164人点赞
     
     
    "小礼物走一走,来简书关注我"
    还没有人赞赏,支持一下
    CoderSJun一个小coder 希望和大家交流编程中的问题和总结
    总资产14 (约1.17元)共写了6023字获得178个赞共61个粉丝
     

    被以下专题收入,发现更多相似内容

  • 相关阅读:
    wso2使用
    wso2安装
    CLR 编译函数的两种结果的原因
    hduoj4311
    通过Git在本地局域网中的两台电脑间同步代码
    Git基本操作之强制推送覆盖仓库
    设置Mac共享网络给其他设备
    谷歌浏览器设置无图浏览模式
    加载到SGA中的库缓存对象超过阈值
    webBrowser 禁止屏蔽alert confirm open showModalDialog
  • 原文地址:https://www.cnblogs.com/sundaysgarden/p/13232967.html
Copyright © 2011-2022 走看看