iOS websocket接入的简单使用

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

接触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
然后在需要开启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:)yesOrNo;
8月10日 更新demo地址
demo地址
可以下载下来看看哦 )


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

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6