WebSockets Tutorial
Introduction to WebSockets
WebSockets provide a full-duplex communication channel over a single, long-lived connection. This is particularly useful for applications that require real-time updates, such as chat applications, online gaming, and live data streaming.
Setting Up a WebSocket Server
To create a WebSocket server, you can use various server-side technologies. Here, we'll demonstrate using Node.js and the ws
library.
npm install ws
Create a file named server.js
and add the following code:
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', socket => {
console.log('Client connected');
socket.on('message', message => {
console.log(`Received: ${message}`);
socket.send('Hello from server');
});
socket.on('close', () => {
console.log('Client disconnected');
});
});
console.log('WebSocket server is running on ws://localhost:8080');
Connecting to a WebSocket Server
To connect to the WebSocket server from a client, you can use the WebSocket API available in modern browsers.
Add the following code to your HTML file:
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Client</title>
</head>
<body>
<h1>WebSocket Client</h1>
<script>
const socket = new WebSocket('ws://localhost:8080');
socket.onopen = () => {
console.log('Connected to the server');
socket.send('Hello from client');
};
socket.onmessage = event => {
console.log(`Message from server: ${event.data}`);
};
socket.onclose = () => {
console.log('Disconnected from the server');
};
</script>
</body>
</html>
Handling WebSocket Events
WebSocket connections have several events you can handle:
onopen
: Triggered when the connection is established.onmessage
: Triggered when a message is received from the server.onclose
: Triggered when the connection is closed.onerror
: Triggered when an error occurs.
Advanced WebSocket Features
WebSockets also support binary data transmission, which can be useful for sending files, images, or other binary data. Here is a basic example of sending binary data:
Server-side:
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', socket => {
socket.on('message', message => {
if (typeof message === 'string') {
console.log(`Received text: ${message}`);
} else if (message instanceof Buffer) {
console.log(`Received binary data: ${message.length} bytes`);
}
});
socket.send(Buffer.from('Hello from server'));
});
console.log('WebSocket server is running on ws://localhost:8080');
Client-side:
const socket = new WebSocket('ws://localhost:8080');
socket.onopen = () => {
console.log('Connected to the server');
const binaryData = new Uint8Array([1, 2, 3, 4, 5]);
socket.send(binaryData);
};
socket.onmessage = event => {
if (typeof event.data === 'string') {
console.log(`Message from server: ${event.data}`);
} else if (event.data instanceof Blob) {
console.log('Received binary data from the server');
}
};
socket.onclose = () => {
console.log('Disconnected from the server');
};
Securing WebSockets
To secure WebSocket connections, use the wss://
protocol instead of ws://
. This ensures that the data transmitted is encrypted using TLS/SSL.
Example of a secure connection:
const socket = new WebSocket('wss://your-secure-websocket-server');
Conclusion
WebSockets provide a powerful way to create real-time, interactive applications. By understanding the basics of setting up a WebSocket server, connecting to it, handling events, and securing your connections, you can build robust and efficient applications that require real-time communication.