Use of websocket (1)


Websocket is a network communication protocol

1: Front page

//Websocket is a communication protocol between client and server, which is different from Ajax communication. Ajax communication (using timer) is that the client sends a request to the server, and the server makes a response to the data return.
            //The websocket server sends data to the client actively, and real-time data interaction is required in the use scenarios, such as location application, online education, smart home and other scenarios that need high real-time.

//Front end
//① Event callback on connection state
var onOpen = function(event){

    var msg = {
        type: "message12222",
        text: "something",
        id: "number",
    this.abj = event.type;
    `//Send can send a string, blob or arraybuffer to the background. When an object is fixed in, it is serialized by using JSON`
`//② Event callback when closing state`
var onClose = function(event){
`// ③ event callback with background return value`
var onMessage = function(data){
    Here, we can get the data returned from the background to the front end and make corresponding processing in the front end.

`// ④ event callback in error state`
var onError = function(event){
`//Interface response`
var ws = new WebSocket('ws://');
`//Function of response`
ws.onopen = onOpen;
ws.onclose = onClose;
ws.onerror = onError;
ws.onmessage = onMessage;

2: Here’s how to use node.js Built back end page

//// WS module required
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({port:8080});

wss.on('connection',function(ws) {
    ws.on('message',function(message) {
    `//Get the value returned by the front end`
        var obj = JSON.parse(message);
    `//Send to front`
    ws.send('hello world');

3: Page display
This node app (the node file customized by app)
Use of websocket (1)