Front End Training - Intermediate Stage (25) - Web Socket Network Programming (Issues 2019-11-14)

The most basic front end is HTML+CSS+Javascript.Having mastered these three technologies, even if you are getting started, is just getting started. Now the definition of front-end development is much more than that.Front-end small classes (HTML/CSS/JS), with the central idea of upgrading technical level and basic knowledge, we have classes (every Thursday).

I wanted to start this content long ago, but the service didn't run before.So the article wasn't written.After an afternoon today, the drums are finally ready demo address

websocket

WebSockets help browsers communicate with servers in both directions.
Before the advent of webSocket s, we needed special means such as polling and long connections to receive data from the server.

Constructor

var protocol = 'wss'
if(location.protocol == "http:") protocol = 'ws'
ws = new WebSocket(protocol+"://ws.lilnong.top");

A connection is made when a WebSocket(url[, protocols]) passes in the URL of the webScoket service.

Properties and methods

Name type describe
url attribute Absolute path of current connection
protocol attribute Subordinate protocol, corresponding to the second parameter of the constructor
readyState attribute Current Link Status
bufferedAmount attribute Absolute path of current connection
binaryType attribute Data type: blob
close() Method Close the current link
send() Method Send data to server

readyState status code

constant numerical value describe
WebSocket.CONNECTING 0 Connecting
WebSocket.OPEN 1 Connected and able to communicate in both directions
WebSocket.CLOSING 2 Closing
WebSocket.CLOSED 3 Closed or unsuccessful connection

WebSocket.send() method

WebSocket.send(String | ArrayBuffer | Blob | ArrayBufferView);

var protocol = 'wss'
if(location.protocol == "http:") protocol = 'ws'
wsTest = new WebSocket(protocol+"://ws.lilnong.top");
wsTest.onclose = ()=>console.log('onclose');
wsTest.onerror = ()=>console.log('onerror');
wsTest.onmessage = ()=>console.log('onmessage');
wsTest.onopen = ()=>console.log('onopen')

var blob = new Blob(['lilnong.top','A batch of water'])
filereader = new FileReader()
filereader.readAsArrayBuffer(blob);
filereader.onload = function(){
    wsTest.send(filereader.result)
    wsTest.send(new Int8Array(filereader.result))
}
wsTest.send(blob)
wsTest.send('lilnong.top Batch 1 of water')

You can see that the blob actually failed to send.Generally speaking, we send String s mostly.

WebSocket.close() method

WebSocket.close([code] [, reason]);

  1. Code indicates an error code.The default is 1005. CloseEvent
  2. reason is the description of the error code.

callback

Function Name Trigger timing Remarks
onclose Callback function when connection is closed Both active and passive close s trigger
onerror Callback function after connection failure Only passive close triggers
onmessage Callback function when receiving data from the server Information returned by e.data for the server
onopen Callback function when connection succeeds You can then interact

Realization

node

Dependent ws = require('ws'); this websocket module.
We can save the connection objects in the connection to a global array.So we can broadcast the message.
Move the connection object out of the array at close.

var ws = require('ws');
var socketServer = ws.Server;
var wss = new socketServer({port: 8090});//Create a service to listen on port 8090
// Listening Connections
wss.on('connection', function(ws){
    // Push message
    ws.send(JSON.stringify({type: 'start',time: Date.now()}))
    // Receive messages from browser
    ws.on('message',function(message){
        console.log(JSON.parse(message))
    })
    // Listening disconnect
    ws.on('close', function() {})
})

html

var initWs = function initWs(){
    var protocol = 'wss'
    if(location.protocol == "http:") protocol = 'ws'
    ws = new WebSocket(protocol+"://ws.lilnong.top");
    ws.onopen = function (e) {console.log('Connection Successful');}
    //Received message processing
    ws.onmessage = function (e) {
        console.log(e.data)
    }
    //Listen for connection closures
    ws.onclose = function (e) {
        setTimeout(v=>initWs(), 2000);//Automatic reconnection
        console.log('Connection closed');
    }
}
initWs();
setInterval(v=>{ws.send(JSON.stringify({type: 'ping'}));}, 10 * 1000);// Keep your heart beating

summary

  1. A socket needs to save the heartbeat, typically ping and pong logic.
  2. Timeout can be set artificially, so the heartbeat time is optional.(My heart beat is 10s because I have 20s.5m that the company did before).
  3. Sockets should be reconnected when disconnected.Because they all fall inside the close, we can reconnect directly inside the close.

    1. In some cases, attention should be paid to the strategy of the frequency and number of reconnections.
  4. Send and receive can only be strings, so JSON.stringify()

WeChat Public Number: Front End linong

Reference

  1. Front End Training Catalogue, Front End Training Planning, Front End Training Planning
  2. WebSockets

Keywords: Javascript Attribute JSON socket

Added by xdracox on Fri, 08 Nov 2019 02:08:10 +0200