📅  最后修改于: 2023-12-03 15:05:55.540000             🧑  作者: Mango
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.
Real-time Communication: WebSockets provide real-time communication between a client and a server, which is not possible with traditional HTTP.
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.
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.
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.
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!');
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.
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.