Precautions for using iOS SocketIO

introduction

Recently, the project has to switch to socketio. I changed it once before. Because I didn’t take notes, I spent a lot of time looking for information and problem solving methods. I have to go through it again, and I must record it! ! ! The records of stepping and filling pits during use are convenient for future search.

text

Given that there is no iOS version of socketio now, there is only a swift version.

There are several questions:

1. Import the framework Socket.io-client-Swift ( mirror address ), ( GitHub address ) referenced by the OC project

2. Bridge between OC language and Swift language

3. Some things to pay attention to

1. Import socket.io-client-swift

It is recommended to use cocopods import! ! !

I use pure code to import something wrong and I don’t know how to solve it. I am lazy and waste time.

There are many tutorials on how to use cocopods, but I will repeat them here.

Let's start directly from the project that has configured cocopods:

ps: I dislike the trouble of compiling Profile files in the terminal, and I am lazy in the operation steps.

  • First open the podfile in the project and add this line directly
pod 'Socket.IO-Client-Swift'
  • Open the terminal --> cd to the project folder
cd /Users/q/Desktop/项目 
  • Update profile import
pod install

 After the update is complete, the socketio-related SDKs are imported into the project

 2. OC and Swift bridging

Since SocketIO uses the Swift framework, a bridge must be established

  • First create a Swift file, and you will be prompted whether to create a bridging file when you create it for the first time.

  •  After the project is created, there will be two more files, as shown in the figure

 3. use

  • Import the SocketIO framework in the bridge file
@import SocketIO;
  •  Import the bridging file header file in the file that needs to be used
#import "项目-Bridging-Header.h"
#import "项目-Swift.h" //编译文件
  •  Used in the project, this parameter comparison table is very important and very helpful for use. Attached source of comparison table
 /**

     log 是否打印日志
     forceNew      这个参数设为NO从后台恢复到前台时总是重连,暂不清楚原因
     forcePolling  是否强制使用轮询
     reconnectAttempts 重连次数,-1表示一直重连
     reconnectWait 重连间隔时间
     connectParams 参数
     forceWebsockets 是否强制使用websocket, 解释The reason it uses polling first is because some firewalls/proxies block websockets. So polling lets socket.io work behind those.
     
**/

    NSURL* url = [[NSURL alloc] initWithString:IP_URL];
    SSLSecurity *SSLSecu = [[SSLSecurity alloc]initWithUsePublicKeys:YES];
    self.manager = [[SocketManager alloc]initWithSocketURL:url config:@{@"log": @YES, @"selfSigned":@YES,@"securty":SSLSecu,@"forceNew" : @YES, @"forcePolling": @NO, @"reconnectAttempts":@(-1), @"reconnectWait" : @1, @"connectParams": @{@"userId" : token}, @"forceWebsockets" : @NO}];
    SocketIOClient *socket = self.manager.defaultSocket;
  •  "Identification" of some methods and event handlers
// socket 连接服务器
	[socket on:@"connect" callback:^(NSArray* data, SocketAckEmitter* ack) {
	    NSLog(@"socket connected ");
	            [weakSelf.socket handleEvent:@"authenticated" data:data isInternalMessage:NO withAck:1]; // 添加接收鉴权的方法
	}];
	[socket connect];
// socket 鉴权 看情况使用
    [socket on:@"authenticated" callback:^(NSArray * data, SocketAckEmitter * ack) {
        if (data.count > 0) {
            NSLog(@"socket 鉴权结果 - %@",data);
        }
    }];
// 心跳包 具体情况看服务端发送和接收方式
    [socket on:@"ping" callback:^(NSArray * _Nonnull data, SocketAckEmitter * _Nonnull ack) {
        NSLog(@"socket - 心跳包");
        // 查看socket 连接状态
        NSLog(@"connect manager status  : %ld",(long)weakSelf.manager.status);
    }];
  // socket 断开连接
    [socket on:@"disconnect" callback:^(NSArray* data, SocketAckEmitter* ack) {
        // 断开连接
        NSLog(@"socket.io disconnect   断开连接");
        // 添加条件判断 超过5次断开连接
        if (weakSelf.connectCount > 5) {
            [weakSelf closeSocket];
        }
    }];
    
    [socket on:@"reconnect" callback:^(NSArray *data, SocketAckEmitter *ack) {
        NSLog(@"重连中...");
        if (data.count > 0) {
        // 连接成功
            weakSelf.connectCount = 0;
        }else
        {
	        // 连接失败
            weakSelf.connectCount++;
        }
        if (weakSelf.connectCount > 5) {
            [weakSelf closeSocket];
        }
        
    }];
    //连接出错了
    [_socket on:@"error" callback:^(NSArray * data, SocketAckEmitter * ack) {
        NSLog(@"socket.io error %@",data);
    }];

// 关闭socket
-(void)closeSocket{
    if (_socket) { // 如果socket 存在 再关闭 
        self.connectCount = 0;
        // 发送关闭socket 请求
        [_socket emit:@"disconnect_request" with:@[]]; 
        [_socket disconnect];
        _socket = nil;
    }
}

over!

Guess you like

Origin blog.csdn.net/hezhi66327/article/details/128557944