
Raspi Websocket in NodeJs
Setting up WebSocket on Raspberry Pi using Node.js lets you create real-time, two-way communication between your Pi and a web browser or other device. Perfect for IoT projects like live sensor data, remote control, or even a smart dashboard! ๐กโจ
๐ฏ What Youโll Build
A simple WebSocket server on the Pi that lets your browser send/receive data instantly โ without refreshing the page.
๐ฆ Step 1: Project Setup
const express = require('express');const http = require('http');const socketIo = require('socket.io');const app = express();const server = http.createServer(app);const io = socketIo(server);// Serve static filesapp.use(express.static('public'));io.on('connection', (socket) => { <!DOCTYPE html>const socket = io(); socket.on('connect', () => { log('๐ข Connected to Raspberry Pi'); }); socket.on('messageFromServer', (msg) => { log('๐ฌ Pi says: ' + msg); }); function sendMessage() { const msg = document.getElementById('msgInput').value; socket.emit('messageFromClient', msg); log('๐ค Sent: ' + msg); } function log(message) { const div = document.createElement('div'); div.textContent = message; document.getElementById('log').appendChild(div); } </script></body></html>
๐ Step 4: Run the Server
sudo node server.js
Then open your browser at:
๐ http://<your-raspberry-pi-ip>:3000
๐ฎ Try It Out
Type a message in the input box and click Send
The Pi logs it and sends a message back
It appears instantly in the browser (no reloads!)
๐ง What Can You Build With This?
Control GPIO devices in real-time (LEDs, motors, relays)
Live sensor dashboards (temperature, motion, etc.)
Mobile app communication with Raspberry Pi
Smart home control panels