📜  WebSockets - Javascript (1)

📅  最后修改于: 2023-12-03 15:05:55.540000             🧑  作者: Mango

WebSockets - Javascript

Introduction

WebSockets is a protocol that provides full-duplex communication channels over a single TCP connection between a client and a server. It is necessary to use WebSockets when real-time data is needed to be exchanged between a server and a client.

Advantages of WebSockets
  1. Real-time Communication: WebSockets provide real-time communication between a client and a server, which is not possible with traditional HTTP.

  2. Low Latency: The latency of WebSockets is significantly lower than HTTP requests since once a WebSocket connection is established, the server can send data to the client immediately.

  3. Increased Efficiency: WebSockets reduce the number of unnecessary requests made to the server, and hence reduce network traffic and increase the efficiency of data transmission.

  4. Bi-Directional Communication: WebSockets allow bi-directional communication between a client and a server, which means both a client and server can send and receive data at any time.

Getting Started with WebSockets in JavaScript
Client Side Implementation

To create a WebSocket connection from the client side, we can use the WebSocket API provided in the browser.

const socket = new WebSocket('ws://localhost:3000');

We can use the onopen event to detect when the WebSocket connection is opened, and the onmessage event to receive data from the server.

socket.onopen = () => {
  console.log('WebSocket connection established!');
}

socket.onmessage = (event) => {
  console.log(`Message received from server: ${event.data}`);
}

To send data to the server, we can use the send method.

socket.send('Hello, server!');
Server Side Implementation

To create a WebSocket server in Node.js, we can use the ws package.

const WebSocket = require('ws');

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

server.on('listening', () => {
  console.log('WebSocket server listening on port 3000!');
});

server.on('connection', (socket) => {
  console.log('WebSocket connection established!');

  socket.on('message', (data) => {
    console.log(`Message received from client: ${data}`);

    socket.send('Hello, client!');
  });
});

We can use the ws package to create a WebSocket server that listens on port 3000. When a WebSocket connection is established, the connection event is fired, and we can use the message event to receive data from the client.

Conclusion

WebSockets are a powerful tool for real-time communication between a client and a server in JavaScript. With low latency, increased efficiency, and bi-directional communication, it is an ideal choice for developing applications that require real-time data exchange.