WebSocket is a communications protocol that enables full-duplex communication over a single, possibly long-lived connection. This entails that either the server's client can send messages to the other, regardless of waiting for a response from the other. WebSocket finds its uses in communication applications involving real-time transfer or real-time data, such as chat applications, live scoreboards, online gaming systems, financial tickers, etc.
How WebSocket Works
WebSocket also runs within a TCP connection to maintain an open data connection between client and server. Here's a simplified overview of how it works:
- Handshake:
- The communication starts as a handshake, an HTTP request from the client to the server.
- The server automatically replies to the request with an HTTP 101 status, which is expected as the connection will switch to WebSocket.
- This request also contains an Upgrade header that tells the server that the client wants to open a WebSocket connection.
- Establishing the Connection:
- Following the handshake process, a two-way connection is maintained actively.
- Both parties can now send and receive messages within the given application independently of HTTP requests.
- Once the client-server handshake creates a connection, the client and server can send and receive full, bidirectional messages.
- This link is therefore full-duplex, and both parties can send information simultaneously.
- Communication:
- Messages are sent in frames. Within each frame is a Brief header section showing what type of data is being transmitted – text or Binary data – before the actual payload data.
- Our interaction on WebSocket frames is much lighter than traditional HTTP requests and responses.
- Data Frames:
- Any communication occurs through frames, simply a segmented package of data.
- Frames can be text or binary data.
- Closing the Connection:
- Either side, the client or the server, can choose to close the connection. The initiator sends a control frame to express that a connection should be closed.
- The other party responds with a closing frame, and the line is dropped, but not before writing a report.
Benefits of WebSocket
- Real-Time Communication:
- Allows data transfer at a moment's notice; suitable for real-time data processing.
- Efficiency:
- One overhead is reduced compared to other HTTP polling, where the server and the client have many requests and feedback.
- Low Latency:
- Delivers lower latency since keeping only one connection to exchange data is possible.
- Bidirectional Communication:
- Both the client and server can send messages to each other independently.
- Scalability:
- Well-suited for applications that require a large volume of concurrent connections.
WebSocket Use Cases
- Chat Applications:
- It allows users to communicate directly in real time.
- Live Sports Updates:
- Give fans scores and game posts.
- OreportsGaming:
- Real-time can support multiple players performing simultaneously.
- Financial Tick Data:
- Provides live stock prices and financial markets.
- Collaborative Tools:
- Enhances synchronous interaction in awareness tools, productivity apps such as document editing, and tools used in project management.
Implementing WebSocket
Here's a basic example of how to implement WebSocket in a Node.js server using the ws
library:
- Install the ws Library:
npm install ws
- Create a WebSocket Server:
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: ${message}`);
socket.send('Message received');
});
socket.on('close', () => {
console.log('Client disconnected');
});
});
console.log('WebSocket server is running on ws://localhost:8080');
- Create a WebSocket Client:
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Client</title>
</head>
<body>
<script>
const socket = new WebSocket('ws://localhost:8080');
socket.onopen = () => {
console.log('Connected to the server');
socket.send('Hello Server');
};
socket.onmessage = (event) => {
console.log(`Message from server: ${event.data}`);
};
socket.onclose = () => {
console.log('Disconnected from the server');
};
</script>
</body>
</html>
Security Considerations
While WebSocket offers many advantages, it is essential to consider security:
- Cross-Site WebSocket Hijacking:
- Make the WebSocket connection available only for authorized users; otherwise, restrict such access.
- Encryption:
- Use Secure WebSocket (wss://) to encrypt data over the WebSocket connection.
- Input Validation:
- Filters all incoming data to exclude any injection attacks.
- Origin Checking:
- Ensure the ebSocket handshake request source is authenticated to avoid illicit connection requests.
Conclusion
WebSocket is an advantageous technology that allows clients and servers to push messages to each other synchronously. Due to its high efficiency and slight delay, this network is suitable for applications where data exchange is used to create functional web applications that can deliver a richer experience to the users while at the same time ensuring that the workings of this technology are as secure as possible.
Read only Understanding WebRTC: Real-Time Communication for Modern Web Applications