Wechat applet socket.io Instant messaging development (based on E-chat SDK)

Keywords: Javascript SDK socket git Webpack

1. Background:

Because wechat applets need to be developed in light weight, cross platform and short development time, many companies regard applets as the first APP for business presentation. The communication part of E-chat client core SDK has been adapted to wechat applet platform. Let's share the ideas and methods in the adaptation process.

2. Analysis:

Wechat applet access requirements: wechat applet mainly supports two communication modes: https and wss. The former is used for api single request, and the latter is used for long connection. Before going online, the domain name address of the server must be configured on the background configuration page of the applet (required for filing, not IP address) to request the back-end server, otherwise the request will be blocked.
E-chat communication mode: E-chat uses http connection and socket.io The former is used for common api requests (such as adding friends, sending messages); the latter is used for real-time communication (such as receiving real-time messages, receiving system notifications).

Conclusion: the api request is implemented on the basis of wechat https and wss socket.io To realize the function of real-time communication.

2. Development access:

2.1 create a new "cloud development demo" and configure "illegal domain name verification" in wechat applet developer tool


In this way, you can temporarily bypass the detection of the filed domain name in the applet and use ip or your own domain name for debugging.

2.2 download the core code of E-chat SDK client and compile the applicable echatim of the applet platform- sdk.js

git clone https://gitee.com/dzqmeiji/echatim-client-ts-core.git
cd echatim-client-ts-core
git checkout -b v1.01 v1.01 # checkout v1.01
yarn install
yarn wxlib # Compile echatim- sdk.js (for windows Platform: set platform = Wx & & webpack -- mode = Production -- config. / build/ webpack.lib.config .js)

2.3 access to E-chat core SDK

Create a new utils directory in the cloud development demo miniprogram directory, which will generate the echatim in the previous step- sdk.js Put it in the utils directory, and the final result is as follows:

Develop demo miniprogram / page in the cloud/ index.js Add sdk configuration related codes under the file, and initialize e-chat sdk in onLoad:

const app = getApp()
var sdk = require('../../utils/echatim-sdk.js');

function initEasyIMSDKWithConfig() {
  const sdkConfig = {};
  sdkConfig.host = 'api.echatim.cn';
  sdkConfig.httpPort = 58082;
  sdkConfig.socketPort = 59092;
  sdkConfig.key = 'TSDKTEST00001';
  sdkConfig.secret = '';
  sdkConfig.apiTransport = 'HTTP';
  sdkConfig.loginAuid = 'admin';
  sdkConfig.loginToken = 'admin';
  sdkConfig.fileServerConfig = {
      use: 'local',
      client: 'plupload',
      baseUrl: 'http://api.echatim.cn:58082',
      version: 'v1',
  };
  initEasyIMSDK(sdkConfig);
}
function initEasyIMSDK(sdkConfig) {
  if (sdk.im === undefined) {
      console.error("Not found echatim sdk, please import echatim-sdk.js first.");
      return;
  }
  var im = sdk.im;
  im.init(sdkConfig, function (sdk) {
      if (sdk) {
          console.log(sdk);
          console.info('echatIMSDK Successfully connected, have access to sdk.apis Data requested.');
      } else {
          throw Error("echatIMSDK initialization failed");
      }
  });
}


Page({
// ... omit code
  onLoad: function() {
    console.log(sdk);
    // Initialize E-chat SDK
    initEasyIMSDKWithConfig();
  }

// ... omit code
})

Rerun the applet project. The terminal output "echaitimsdk successfully connected" indicates that the e-chat sdk has successfully established the connection

3. Principle of adapting wechat applet:

Because e-chat sdk requires cross platform support for Web, wechat applets, react native and other platforms, it is necessary to extract platform related codes for separate processing, and compile different sdk codes according to different platforms.

Please refer to: Conditional compilation of E chat SDK under TypeScript

3.1 join the http access connection of wechat applet platform

In source code HttpApi.ts In httpfetch, add the support part of wechat applet.

    private httpFetch(url:string, request:any):Promise<ApiResponse<V>>{
        /*IFTRUE_WXAPP*/
        // @ts-ignore
        if(wx === undefined){
            throw new Error('wx handle not exist');
        }
        return new Promise<ApiResponse<V>>(function (resolve, reject) {
            // @ts-ignore
            wx.request({
                method: request.method,
                url: url, 
                data: Beans.bean(request.body),
                header: request.headers,
                success (res) {
                    // console.log(res.data)
                    resolve(res.data);
                },
                fail(res){
                    // console.error(res.data)
                    reject(res.data);
                }
            });
        });
        /*FITRUE_WXAPP*/
// ... omit code
}

3.2 add the socket.io connect.

In source code Socket.ts In connect, add the support part of wechat applet.

            /*IFTRUE_WXAPP*/
        const wxio = require('weapp.socket.io');
        this.socket = wxio.connect(url+"");
        /*FITRUE_WXAPP*/

Here we use a wechat applet socket.io Open source plug-ins: https://github.com/weapp-socketio/weapp.socket.io

3.3 add file upload function supporting wechat applet platform (business function is not implemented in version 1.01)

In source code FileServerClient.ts In fileserverclientfactory, add the support part of wechat applet (version 1.01 has no business function yet).

/*IFTRUE_WXAPP*/
            throw new Error(`not support wechat app platform`);
/*FITRUE_WXAPP*/

4. Summary:

  1. Wechat applet supports HTTPS and WSS. E chat SDK can adapt to applet platform;
  2. E-chat SDK has good cross platform support at the beginning of design.

5. Reference:

Wechat applet socket.io
Conditional compilation of E chat SDK under TypeScript

Posted by gskaruz on Sat, 13 Jun 2020 23:47:43 -0700