Recently, I used Rongyun to develop chat pages. Through packet capture, I found that The SDK of Rongyun uses WebSocket to communicate with the server, so I have a brief understanding of the use of WebSocket

WebSocket is needed for:

Summary: HTTP protocol can only be initiated by the client and responded by the server. WebSocket can be initiated by the server or the client. There are more and more complex scenarios that can be implemented

Relevant information is as follows:

Rongyun development document: docs.rongcloud.cn/v4/

WebSocket Web API: developer.mozilla.org/zh-CN/docs/…

WebSocket Node API: socket. IO, WS, uWebSockets (choose one)

Cloud caught

Test address: rongcloud. Making. IO/websdk – demo…

According to packet capture, rongyun links websocket with appKey, token, and SDK version information

Next, implement a simple client + server example

Nodejs server

This example uses the WS module

Create a link:

const Port = '2928'; const wss = new WebSocket.Server({ port: Port }); wss.on('connection', function (ws, event) { const url = event.url; // Url is the client link address, which can be spliced parameters. For example, rongyun spliced appkey and other information:? Appid = n19XXxxxx &token= XXXXXXXX /* Listen link closed */ ws.on('close', () => {// this ws link is broken. Do something}); });Copy the code

Listening for client messages:

const Port = '2928'; const wss = new WebSocket.Server({ port: Port }); wss.on('connection', function (ws, event) { ws.on('message', function (data) { console.log('data', data); // Receive data from client do something}); });Copy the code

Send a request to the client:

const Port = '2928'; const wss = new WebSocket.Server({ port: Port }); wss.on('connection', function (ws, event) { ws.send('some data'); });Copy the code

The Web client

For details about the API, see WebSocket

Build a link:

const socket = new WebSocket('ws://localhost:2928'); Socket.addeventlistener ('open', function (event) {// Connect successfully, do something});Copy the code

Listening for server messages:

const socket = new WebSocket('ws://localhost:2928'); Socket.addeventlistener ('message', function (event) {console.log(' received data from server ', event.data); });Copy the code

Send a request to the server:

const socket = new WebSocket('ws://localhost:2928'); socket.addEventListener('open', function (event) { socket.send('some data'); // After the link, call send});Copy the code