The first step is to initialize the WebSocket object

Ws = new WebSocket(' ws://www.test.com/send_message/${id}-${name} '); Ws = new WebSocket(' WSS ://www.test.com/send_message/${id}-${name} ');Copy the code

Step 2 Establish a connection with the server

Thate.ws.onopen = function () {console.log(” connect to server successfully “)};

Step 3 The server pushes a message

this.ws.onmessage =function (ev) { that.talking(ev.data); } talking () {// process data}

Error trigger occurs in step 4

This.ws. Onerror = function () {console.log(” connection error “)};

Step 5 Turn off the trigger normally

This.ws. Onclose = function () {console.log(” connection closed “); };

Step 6 Send data

this.ws.send(JSON.stringify(json))
Copy the code

Step 7 Close the connection

window.onbeforeunload = ()=> { that.ws.close(); Console. log(' Thanks for coming 1'); Return (' Thank you for coming 2'); // Internet Explorer Google prompt (Opera only refresh prompt)}Copy the code