webSocket usage details

WebSocket is a protocol for two-way communication between a web browser and a server. It allows real-time, bi-directional communication over a persistent TCP connection. The WebSocket protocol is a new technology in HTML5, which can be used to replace traditional polling and long polling methods. This article will introduce the usage of WebSocket in detail and provide code examples.

Basic usage of WebSocket

Create a WebSocket object
To use WebSocket, you need to create a WebSocket object. A WebSocket object can be created by calling the WebSocket constructor. The constructor accepts as a parameter a URL pointing to the WebSocket server to connect to. Here is an example of creating a WebSocket object:

const socket = new WebSocket("ws://localhost:8080");

In this example, we create a WebSocket object named socket and connect it to ws://localhost:8080.

WebSocket events

The WebSocket object provides several events to handle the different phases and states of the WebSocket connection. The following are some commonly used WebSocket events:

  • open: Triggered when a WebSocket connection is successfully opened.
  • message: Triggered when a message from the WebSocket server is received.
  • error: Triggered when an error occurs in the WebSocket connection.
  • close: Triggered when the WebSocket connection is closed.

Different states of WebSocket can be handled by assigning callback functions to these events. Here is an example of handling WebSocket events:

const socket = new WebSocket("ws://localhost:8080");

socket.addEventListener("open", () => {
    
    
  console.log("WebSocket连接已打开");
});

socket.addEventListener("message", (event) => {
    
    
  console.log("收到消息:", event.data);
});

socket.addEventListener("error", () => {
    
    
  console.error("WebSocket连接发生错误");
});

socket.addEventListener("close", () => {
    
    
  console.log("WebSocket连接已关闭");
});

In this example, we use the addEventListener method to assign callback functions to the open, message, error and close events.

Send a message

To send a message to a WebSocket server, use the send method of the WebSocket object. The method accepts a string parameter which will be sent to the server as a message. Here is an example of sending a message:

const socket = new WebSocket("ws://localhost:8080");

socket.addEventListener("open", () => {
    
    
  console.log("WebSocket连接已打开");
  socket.send("Hello, server!");
});

socket.addEventListener("message", (event) => {
    
    
  console.log("收到消息:", event.data);
});

In this example, we use the send method to send a message to the server when the WebSocket connection is opened.

close connection

To close a WebSocket connection, you can use the close method of the WebSocket object. An optional status code and reason string can be passed to this method. Here is an example of closing a WebSocket connection:

const socket = new WebSocket("ws://localhost:8080");

socket.addEventListener("open", () => {
    
    
  console.log("WebSocket连接已打开");
});

socket.addEventListener("message", (event) => {
    
    
  console.log("收到消息:", event.data);
  socket.close();
});

socket.addEventListener("close", () => {
    
    
  console.log("WebSocket连接已关闭");
});

In this example, we use the close method to close the WebSocket connection after receiving a message.

Advanced usage of WebSocket

Using WebSocket Protocol Extensions
WebSocket protocol support uses WebSocket extensions to enhance the functionality of WebSocket. These extensions can be negotiated during the handshake so that the client and server use the same extension. Here is an example using the WebSocket protocol extension:

const socket = new WebSocket("ws://localhost:8080", "chat");

socket.addEventListener("open", () => {
    
    
  console.log("WebSocket连接已打开");
});

socket.addEventListener("message", (event) => {
    
    
  console.log("收到消息:", event.data);
});

socket.addEventListener("close", () => {
    
    
  console.log("WebSocket连接已关闭");
});

In this example, we pass chat as the second argument to the constructor when creating the WebSocket object. This indicates that we want to use the chat extension in the WebSocket protocol.

Using the WebSocket subprotocol

The WebSocket protocol also supports the use of sub-protocols to enhance the functionality of WebSocket. The subprotocol is negotiated during the handshake and persists for the duration of the connection. Here is an example using the WebSocket subprotocol:

const socket = new WebSocket("ws://localhost:8080", "chat");

socket.addEventListener("open", () => {
    
    
  console.log("WebSocket连接已打开");
});

socket.addEventListener("message", (event) => {
    
    
  console.log("收到消息:", event.data);
});

socket.addEventListener("close", () => {
    
    
  console.log("WebSocket连接已关闭");
});

In this example, we pass chat as the second argument to the constructor when creating the WebSocket object. This indicates that we want to use a subprotocol called chat.

Using WebSocket Binary Data

The WebSocket protocol supports sending and receiving binary data. To send binary data, use the WebSocket.send method and pass an ArrayBuffer or Blob object. To receive binary data, you can use the binaryType property of the WebSocket object. Here's an example using WebSocket binary data:

const socket = new WebSocket("ws://localhost:8080");

socket.binaryType = "arraybuffer";

socket.addEventListener("open", () => {
    
    
  console.log("WebSocket连接已打开");
  const buffer = new ArrayBuffer(8);
  const view = new DataView(buffer);
  view.setInt16(0, 42);
  view.setInt16(2, 1337);
  socket.send(buffer);
});

socket.addEventListener("message", (event) => {
    
    
  console.log("收到消息:", new DataView(event.data));
});

socket.addEventListener("close", () => {
    
    
  console.log("WebSocket连接已关闭");
});

In this example, we set the binaryType property to "arraybuffer" in order to receive ArrayBuffer objects. We also use the ArrayBuffer constructor to create a buffer of 8 bytes and use the DataView object to set the values ​​in the buffer. Finally, we send the buffer to the server using the WebSocket.send method.

Using the WebSocket heartbeat package

WebSocket connections may drop due to network problems or server problems. In order to detect if the connection is broken, the WebSocket heartbeat package can be used. Heartbeat packets are small messages that are periodically sent to the server. If the server does not receive a heartbeat packet for a period of time, it will assume the connection is broken, and close the connection. Here is an example using the WebSocket heartbeat package:

const socket = new WebSocket("ws://localhost:8080");

function sendHeartbeat() {
    
    
  if (socket.readyState === WebSocket.OPEN) {
    
    
    socket.send("heartbeat");
  }
}

socket.addEventListener("open", () => {
    
    
  console.log("WebSocket连接已打开");
  setInterval(sendHeartbeat, 5000);
});

socket.addEventListener("message", (event) => {
    
    
  console.log("收到消息:", event.data);
});

socket.addEventListener("close", () => {
    
    
  console.log("WebSocket连接已关闭");
});

In this example, we define a function called sendHeartbeat, which will send a heartbeat packet every 5 seconds after the WebSocket connection is opened. We also use the setInterval method in the open event handler to call the sendHeartbeat function.

Implementation of WebSocket server side

A WebSocket server is a web server that can communicate with clients using the WebSocket protocol. Here is an example implementing a WebSocket server using Node.js:

import WebSocket from "ws";

const server = new WebSocket.Server({
    
     port: 8080 });

server.on("connection", (socket) => {
    
    
  console.log("WebSocket连接已打开");

  socket.send("Welcome to the server!");

  socket.on("message", (message) => {
    
    
    console.log("收到消息:", message);
    socket.send(`Echo: ${
      
      message}`);
  });

  socket.on("close", () => {
    
    
    console.log("WebSocket连接已关闭");
  });
});

In this example, we created a WebSocket server using Node.js' ws library. We use the Server constructor to create a WebSocket server named server and bind it to port 8080. In the connection event handler, we handle new WebSocket connections. We use the send method to send a welcome message to the client, and use the on("message") method to process the message sent by the client

Guess you like

Origin blog.csdn.net/ZTAHNG/article/details/131474804