WebSockets are a modern web technology that enables real - time communication between a client (usually a web browser) and a server. It operates on top of the TCP protocol and provides a persistent connection. Once the WebSocket connection is established, both the client and the server can send data to each other at any time without the need to open a new connection for each message.
The WebSocket protocol starts with an HTTP handshake, which upgrades the connection from HTTP to WebSocket. After the upgrade, the connection remains open until either the client or the server decides to close it.
In the browser, JavaScript provides a built - in WebSocket
object that can be used to create and manage WebSocket connections. The basic steps to create a WebSocket connection in JavaScript are as follows:
// Create a new WebSocket instance
const socket = new WebSocket('ws://localhost:8080');
// Event listener for when the connection is opened
socket.addEventListener('open', (event) => {
console.log('Connected to the WebSocket server');
});
// Event listener for when a message is received
socket.addEventListener('message', (event) => {
console.log('Received message:', event.data);
});
// Event listener for when the connection is closed
socket.addEventListener('close', (event) => {
console.log('Disconnected from the WebSocket server');
});
On the server - side, in a Node.js environment, libraries like ws
can be used to create a WebSocket server.
First, install the ws
library using npm:
npm install ws
Here is an example of creating a simple WebSocket server using the ws
library:
const WebSocket = require('ws');
// Create a new WebSocket server on port 8080
const wss = new WebSocket.Server({ port: 8080 });
// Event listener for when a client connects
wss.on('connection', (ws) => {
console.log('A client has connected');
// Event listener for when the server receives a message from the client
ws.on('message', (message) => {
console.log('Received message:', message);
// Send a response back to the client
ws.send('Server received your message: ' + message);
});
// Event listener for when the client disconnects
ws.on('close', () => {
console.log('A client has disconnected');
});
});
The following JavaScript code can be used in an HTML file to connect to the WebSocket server created above:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF - 8">
</head>
<body>
<script>
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open', () => {
console.log('Connected to the server');
// Send a message to the server
socket.send('Hello, server!');
});
socket.addEventListener('message', (event) => {
console.log('Received from server:', event.data);
});
socket.addEventListener('close', () => {
console.log('Disconnected from the server');
});
</script>
</body>
</html>
To send a message from the client to the server, you can use the send
method of the WebSocket
object:
// Client - side code
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open', () => {
socket.send('This is a message from the client');
});
On the server - side, you can listen for the message
event to receive messages from the client:
// Server - side code using ws library
wss.on('connection', (ws) => {
ws.on('message', (message) => {
console.log('Received message:', message);
});
});
Both the client and the server should handle connection events such as open
, close
, and error
. For example, on the client - side:
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open', () => {
console.log('Connection opened');
});
socket.addEventListener('close', () => {
console.log('Connection closed');
});
socket.addEventListener('error', (error) => {
console.error('WebSocket error:', error);
});
Proper error handling is crucial in real - time applications. On the client - side, you can handle errors by listening for the error
event of the WebSocket
object. On the server - side, you should handle errors that may occur during the connection process or when sending and receiving messages.
// Client - side error handling
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('error', (error) => {
console.error('WebSocket error:', error);
});
// Server - side error handling using ws library
wss.on('error', (error) => {
console.error('WebSocket server error:', error);
});
wss
protocol instead of ws
. The wss
protocol encrypts the data transmitted over the WebSocket connection, providing an additional layer of security.Building real - time applications with JavaScript and WebSockets is a powerful and efficient way to create engaging user experiences. JavaScript’s flexibility and WebSockets’ ability to provide real - time, bidirectional communication make them a great combination for a wide range of applications. By understanding the fundamental concepts, usage methods, common practices, and best practices, you can build robust and secure real - time applications.