0
0
Raspberry Piprogramming~7 mins

WebSocket for live updates in Raspberry Pi

Choose your learning style9 modes available
Introduction

WebSocket lets your Raspberry Pi talk to a web page instantly. It helps send live updates without waiting.

You want to show sensor data on a webpage as it changes.
You need to control devices from a browser in real-time.
You want to build a chat app that updates messages instantly.
You want to display live notifications or alerts on a webpage.
Syntax
Raspberry Pi
import asyncio
import websockets

async def handler(websocket):
    async for message in websocket:
        await websocket.send(f"Got your message: {message}")

async def main():
    async with websockets.serve(handler, "localhost", 8765):
        await asyncio.Future()  # run forever

asyncio.run(main())

This example uses Python's asyncio and websockets library.

The server listens on port 8765 and sends back messages it receives.

Examples
This server sends a greeting once a client connects, then prints any messages it gets.
Raspberry Pi
import asyncio
import websockets

async def handler(websocket):
    await websocket.send("Hello from Raspberry Pi!")
    async for message in websocket:
        print(f"Received: {message}")

async def main():
    async with websockets.serve(handler, "localhost", 8765):
        await asyncio.Future()

asyncio.run(main())
This example sends sensor data every second to connected clients.
Raspberry Pi
import asyncio
import websockets

async def handler(websocket):
    while True:
        data = get_sensor_data()  # pretend function
        await websocket.send(str(data))
        await asyncio.sleep(1)  # send every second

async def main():
    async with websockets.serve(handler, "localhost", 8765):
        await asyncio.Future()

asyncio.run(main())
Sample Program

This program runs a WebSocket server on your Raspberry Pi. It sends a fake temperature reading every 2 seconds to any connected client.

Raspberry Pi
import asyncio
import websockets
import random

async def handler(websocket):
    while True:
        temp = random.uniform(20.0, 25.0)  # fake temperature
        message = f"Temperature: {temp:.2f} °C"
        await websocket.send(message)
        await asyncio.sleep(2)

async def main():
    async with websockets.serve(handler, "localhost", 8765):
        print("WebSocket server started on ws://localhost:8765")
        await asyncio.Future()  # run forever

asyncio.run(main())
OutputSuccess
Important Notes

Make sure to install the websockets library with pip install websockets.

WebSocket connections stay open, so they use less data than asking the server again and again.

Use localhost for testing on the same device, but use your Pi's IP address for other devices.

Summary

WebSocket lets your Raspberry Pi send live updates to web pages instantly.

It keeps a connection open so data flows both ways without delay.

Use it for real-time sensor data, controls, or notifications.