Use of websocket (1)

Time:2020-6-29

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){

console.log(event);
    var msg = {
        type: "message12222",
        text: "something",
        id: "number",
        time: Date.now()
    };
    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`
    ws.send(JSON.stringify(msg));
};
`//② 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.
    `
    console.log(data);

};
`// ④ event callback in error state`
var onError = function(event){
};
`//Interface response`
var ws = new WebSocket('ws://127.0.0.1:8080/');
`//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`
        console.log(message);
        var obj = JSON.parse(message);
        console.log(obj);
    });
    `//Send to front`
    ws.send('hello world');
})
console.log('running');

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