WebSockets are a powerful tool for creating real-time communication between a server and a client. In this guide, we will walk through setting up a WebSocket server on your Raspberry Pi and connecting it to a web client for interactive, real-time communication. Whether you’re building a live chat application, controlling hardware remotely, or implementing real-time data updates.
What Is WebSocket?
A WebSocket is a protocol that enables two-way, full-duplex communication between a client (usually a web browser) and a server. Unlike traditional HTTP, which is request-response-based, WebSockets allow for continuous, real-time data exchange without the need to constantly open new connections.
- Persistent Connection: WebSocket creates a persistent connection between the client and server.
- Real-Time Data Transfer: Allows immediate communication, ideal for real-time applications.
- Low Latency: Reduces overhead compared to polling or AJAX requests.
Prerequisites
Before diving into the code, ensure you have the following:
- Raspberry Pi: Any model (e.g., Raspberry Pi 4, Zero).
- Raspberry Pi OS: Installed and updated on your Raspberry Pi.
- Python 3.x: Installed on your Raspberry Pi.
- Web Browser: For testing the WebSocket client.
- Internet Connection: For Raspberry Pi and client (optional).
Step 1: Install the WebSocket Server on Raspberry Pi
To start using WebSockets, you need to install the websockets Python library. Open a terminal and run the following command:
pip install websockets
This will install the necessary package to create a WebSocket server on your Raspberry Pi.
Step 2: Write the WebSocket Server Code
In this example, we will create a simple WebSocket server on the Raspberry Pi that listens for client connections and sends a message every time a client connects.
Python Code for WebSocket Server:
import asyncio
import websockets
async def echo(websocket, path):
print(f"Client connected from {path}")
await websocket.send("Hello from Raspberry Pi WebSocket Server!")
try:
while True:
message = await websocket.recv() # Receive message from client
print(f"Received message: {message}")
await websocket.send(f"Echo: {message}") # Send the same message back
except websockets.ConnectionClosed:
print("Client disconnected")
# Start the server
async def main():
server = await websockets.serve(echo, "localhost", 8765)
print("WebSocket server running on ws://localhost:8765")
await server.wait_closed()
# Run the event loop
asyncio.run(main())
Code Explanation:
- import websockets: Imports the WebSocket library for handling WebSocket communication.
- async def echo(websocket, path): A function that handles incoming WebSocket connections. It sends a greeting message to the client and echoes back any messages received from the client.
- await websocket.send(): Sends a message to the client.
- await websocket.recv(): Waits for a message from the client.
- websockets.serve(echo, “localhost”, 8765): Starts the WebSocket server on localhost and port
8765
. - asyncio.run(main()): Runs the asynchronous event loop to start the server.
Step 3: Create the WebSocket Client
Now that the server is running, we will create a simple HTML and JavaScript client to interact with the WebSocket server.
HTML and JavaScript WebSocket Client:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Client</title>
</head>
<body>
<h1>WebSocket Client</h1>
<button id="connect">Connect to Server</button>
<button id="send">Send Message</button>
<div id="messages"></div>
<script>
let socket;
// Connect to the WebSocket server
document.getElementById("connect").onclick = function() {
socket = new WebSocket("ws://localhost:8765");
socket.onopen = function() {
document.getElementById("messages").innerHTML = "Connected to the server!";
};
socket.onmessage = function(event) {
document.getElementById("messages").innerHTML += "<br>Received: " + event.data;
};
socket.onerror = function(error) {
console.error("WebSocket Error: " + error);
};
socket.onclose = function() {
document.getElementById("messages").innerHTML += "<br>Connection closed";
};
};
// Send a message to the server
document.getElementById("send").onclick = function() {
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send("Hello from WebSocket Client!");
} else {
alert("WebSocket is not connected!");
}
};
</script>
</body>
</html>
Client Code Explanation:
- new WebSocket(“ws://localhost:8765”): Creates a WebSocket client that connects to the server running on the Raspberry Pi.
- socket.onopen: Executes when the connection to the server is established.
- socket.onmessage: Handles messages received from the server and displays them in the messages div.
- socket.send(): Sends a message to the WebSocket server when the “Send Message” button is clicked.
Step 4: Run the WebSocket Server and Client
Run the WebSocket Server:
Open a terminal on your Raspberry Pi and run the server script:
python3 websocket_server.py
Open the Client:
Open the HTML file (index.html) in a web browser on your computer or Raspberry Pi.
Test the WebSocket Communication:
- Click “Connect to Server” to establish a WebSocket connection with the server.
- Click “Send Message” to send a message to the Raspberry Pi, and the server will echo it back.
Troubleshooting Common Issues
- Connection Error:
- Ensure the WebSocket server is running and that the correct port (8765) is open.
- Verify that the server address ws://localhost:8765 matches the running server.
- WebSocket Not Sending Messages:
- Make sure the WebSocket connection is open before sending messages. You can check the readyState of the socket.
Real-World Applications
- Real-Time Web Apps: Use WebSockets for live chat applications, stock market updates, or social media feeds.
- IoT Projects: Control devices like sensors and actuators remotely via WebSockets.
- Remote Device Control: Create a remote control system for Raspberry Pi hardware or other devices.