“This is the ninth day of my participation in the First Challenge 2022. For details: First Challenge 2022”

What is a WebSocket?

If Ajax is like SMS, sending and getting information, Websocket is like making a phone call. The goal of WebSocket is to allow users to get real-time updates without having to refresh the browser.

Before WebSocket, you might have used Ajax for polling (including some software that didn’t integrate WebSocket today), which caused a lot of strain on the server, consuming a lot of server bandwidth and resources.

Facing this situation, HTML5 defines the WebSocket protocol, which can better save server resources and bandwidth and realize real time push.

WebSocket protocol is essentially a PROTOCOL based on TCP, which is composed of communication protocol and programming API. WebSocket can establish a bidirectional connection between the browser and the server, and give the browser real-time communication capability in an event-based way. Two-way communication means that both the server and client can send and respond to requests at the same time, unlike HTTP request and response.

WebSocket event

The event describe
Socket.onopen Triggered when the connection is established
Socket.onmessage Triggered when the client receives data from the server
Socket.onerror Triggered when a communication error occurs
Socket.onclose Triggered when the connection is closed

WebSocket method

methods describe
Socket.send() Use the connection to send data
Socket.close() Close the connection

Nodejs + WebSocket example

Here we install the WebSocket module:

npm i nodejs-websocket -S
Copy the code

Create a new index.js server:

var ws = require("nodejs-websocket");
console.log("Start establishing connections...")

var server = ws.createServer(function(conn){
  conn.on("text".function (str) {
    console.log("message:"+str)
    conn.sendText("My name is Web Xiu!");
  })
  conn.on("close".function (code, reason) {
    console.log("Close connection")}); conn.on("error".function (code, reason) {
    console.log("Abnormal shutdown")}); }).listen(8001)
console.log("WebSocket setup completed")
Copy the code

The client

if(window.WebSocket){
  var ws = new WebSocket('ws://localhost:8001');

  ws.onopen = function(e){
    console.log("Server connection successful");
    // Send a message to the server
    ws.send("what`s your name?");
  }
  ws.onclose = function(e){
    console.log("Server down");
  }
  ws.onerror = function(){
    console.log("Connection error");
  }
  // Receive a message from the server
  ws.onmessage = function(e){
    let message = "message:"+e.data+"";
    console.log(message); }}Copy the code

So, the client sends: ws. Send (” Whats your name?” ); Conn. SendText (“My name is Web Xiu!” ); As long as the connection is constantly open, you can always communicate.