WebSocket Sending and Receiving Messages
Overview
In this chapter, we will focus on sending and receiving messages using WebSockets. We will cover how to handle text and binary data, ensuring message integrity, and best practices for communication.
Sending Messages
Sending messages over a WebSocket connection is straightforward. Once the connection is established, you can use the send
method to send data to the server. The data can be in the form of a string or binary data.
Example: Sending Text Messages
document.getElementById('send').addEventListener('click', () => {
const message = document.getElementById('messageInput').value;
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(message);
document.getElementById('messageInput').value = '';
}
});
In this example, we get the message from an input field and send it to the server using the send
method of the WebSocket instance.
Example: Sending Binary Data
WebSockets can also send binary data, such as ArrayBuffer or Blob. This is useful for sending files, images, or other binary data types.
document.getElementById('sendBinary').addEventListener('click', () => {
if (socket && socket.readyState === WebSocket.OPEN) {
const arrayBuffer = new Uint8Array([1, 2, 3, 4, 5]).buffer;
socket.send(arrayBuffer);
}
});
In this example, we create an ArrayBuffer and send it to the server. The server must be capable of handling binary data.
Receiving Messages
To receive messages from the server, you can use the message
event handler. The event's data
property contains the message sent by the server.
Example: Receiving Text Messages
socket.addEventListener('message', (event) => {
console.log('Message from server: ', event.data);
document.getElementById('messages').innerHTML += '<p>' + event.data + '</p>';
});
In this example, we log the received message to the console and display it in the messages div.
Example: Receiving Binary Data
To receive binary data, you need to set the WebSocket's binaryType
property to 'arraybuffer'
or 'blob'
. This tells the WebSocket to treat incoming messages as binary data.
socket.binaryType = 'arraybuffer';
socket.addEventListener('message', (event) => {
if (event.data instanceof ArrayBuffer) {
const array = new Uint8Array(event.data);
console.log('Received binary data: ', array);
} else {
console.log('Received text data: ', event.data);
}
});
In this example, we set the binaryType
to 'arraybuffer'
and check if the received data is an ArrayBuffer. If it is, we convert it to a Uint8Array and log it to the console.
Ensuring Message Integrity
When sending and receiving messages, it's important to ensure that the data is not corrupted or lost. Here are some best practices for ensuring message integrity:
- Use a checksum or hash: Include a checksum or hash with your messages to verify their integrity on the receiving end.
- Implement acknowledgments: Implement an acknowledgment mechanism to confirm that messages are received and processed successfully.
- Handle fragmentation: Be aware that large messages may be fragmented into smaller frames. Ensure that your application can handle reassembling these frames.
Example: Simple Acknowledgment Mechanism
// Client-side code
socket.addEventListener('message', (event) => {
const message = event.data;
console.log('Message from server: ', message);
socket.send('ACK: ' + message); // Send acknowledgment
});
// Server-side code (FastAPI)
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Received: {data}")
ack = await websocket.receive_text()
print(f"Acknowledgment: {ack}")
In this example, the client sends an acknowledgment message back to the server after receiving a message. The server logs the acknowledgment to the console.
Best Practices for Communication
Here are some best practices to keep in mind when sending and receiving messages over WebSockets:
- Keep messages small: Smaller messages are transmitted faster and are less likely to be fragmented.
- Use JSON for structured data: JSON is a lightweight and easy-to-parse format for structured data.
- Handle disconnections gracefully: Implement logic to handle disconnections and attempt reconnections if necessary.
- Secure your WebSocket connection: Use
wss://
to secure your WebSocket connection with SSL/TLS.
Conclusion
In this chapter, we have covered how to send and receive messages using WebSockets. We explored handling text and binary data, ensuring message integrity, and best practices for communication. These techniques will help you build robust and reliable WebSocket applications.
In the next chapter, we will dive into WebSocket security, discussing how to secure your WebSocket connections and protect your application from common security threats.