WebSocket is a communications protocol which enables full-duplex communication over a single, possibly long-lived connection. This entails that either the client of the server can send messages to the other regardless of wait for a response from the other. WebSocket finds its uses in communication applications which involve real time data transfer or real time updates such as chat applications or live score boards for overrunning, online gaming systems or financial tickers etc.
How WebSocket Works
WebSocket also runs within a TCP connection to maintain an open connection of the data between client and server. Here’s a simplified overview of how it works:
- Handshake:
- The communication starts as a handshake which is an HTTP request from the client towards the server.
- The server automatically replies to the request with a HTTP 101 status which is expected as the connection will switch to WebSocket.
- This request also contains Upgrade header that tells the server that the client wants to open a WebSocket connection.
- Establishing the Connection:
- Following the handshake process, via two way connection maintained actively.
- Both parties are now able to send and receive messages within the given application independent of having to use HTTP requests.
- Once a connection is created by the client-server handshake, both the client and server can send and receive full, bidirectional messages.
- This link is therefore full-duplex and both parties can send information simultaneously at any one time.
- Communication:
- Messages are sent in frames. Brief, within each frame, is a Header section showing what type of data is being transmitted – text or Binary data – before the actual payload data.
- Basing our interaction on WebSocket frames is much lighter than traditional HTTP requests and responses.
- Data Frames:
- Any communication takes place through frames, which is 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, to express the fact a connection should be closed.
- The other party responds with a closing frame, and the line is dropped, but not before writing a report on it.
Benefits of WebSocket
- Real-Time Communication:
- Allows the transfer of data at a moment’s notice; suitable for real-time data processing.
- Efficiency:
- Has one overhead reduced when compared to other HTTP polling where there are many requests and feedback between the server and the client.
- Low Latency:
- Delivers lower latency since it is then possible to keep only one connection for the exchange of data.
- Bidirectional Communication:
- Both the client and server can send messages to each other independently.
- Scalability:
- Well suited for application that require a large volume of concurrent connections.
WebSocket Use Cases
- Chat Applications:
- It allow the users directly communicate in real time.
- Live Sports Updates:
- Gives fan immediate scores and gaming report to fans.
- Online Gaming:
- Real time, can support multiple players to perform simultaneously.
- Financial Tick Data:
- Provides live stock prices and financial markets.
- Collaborative Tools:
- Enhances synchronous interaction in awareness tools, productivity apps such as documents 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 important 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 injections attacks.
- Origin Checking:
- Ensure that WebSocket handshake request source is authenticated to avoid illicit connection request.
Conclusion
WebSocket is advantageous technology which allows for clients and servers to push messages to each other synchronously. Due to its high efficiency and small time delay, this network is suitable for application, where data exchange is to occur in real time. This paper has sought to establish how developers can employ this technology to create meaningful web applications that can deliver 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