This project implements a WebSocket server for handling real-time sensor data. It listens for incoming connections, receives sensor data in JSON format, and broadcasts it to all connected clients.
- WebSocket Support: Clients can connect to the server using WebSockets.
- Real-Time Data Broadcasting: Sensor data received from one client is broadcast to all connected clients.
- Local IP Detection: Displays the local IP addresses for easy connection.
- Error Handling: Handles invalid JSON messages gracefully.
Ensure the following software is installed on your system:
-
Node.js (v14 or higher)
You can download Node.js from https://nodejs.org/. -
WebSocket Client (optional for testing)
You can use tools like websocat, browser-based WebSocket clients, or custom scripts to connect to the server.
-
Clone this repository:
git clone <repository_url> cd <repository_folder>
-
Install the required dependencies:
npm install
Run the server with the following command:
node server.jsWhen the server starts, it will display the local IP addresses and the listening port:
Server running at:
- http://<local_IP_1>:8080
- http://<local_IP_2>:8080
Replace <local_IP_1> and <local_IP_2> with the actual local IP addresses displayed in the output.
Clients can connect to the WebSocket server using the following URL:
ws://<server_IP>:8080
Clients can send JSON-formatted sensor data to the server. Example message format:
{
"temperature": 22.5,
"humidity": 65
}The server will broadcast this data to all connected clients.
-
getLocalIP()
Retrieves the local IPv4 addresses of the machine running the server. -
HTTP Server
Serves a basic text response when accessed via a web browser or HTTP client:Sensor Data WebSocket Server -
WebSocket Server
- Listens for incoming WebSocket connections.
- Processes incoming messages:
- Parses and logs sensor data.
- Broadcasts data to all connected clients.
- Handles errors for invalid JSON messages.
-
Error Logging
Logs the raw message and error details if a message fails to parse.
- WebSocket: Provides WebSocket server functionality.
Install with:npm install ws
- HTTP: Built-in Node.js module for handling HTTP requests.
- OS: Built-in Node.js module for accessing network interfaces.
To extend the server, you can:
- Add custom validation for sensor data.
- Implement authentication for secure client connections.
- Log data to a database or file system.
-
Port Already in Use
If port8080is occupied, modify theserver.listencall inserver.jsto use a different port:server.listen(9090, () => { ... });
-
Invalid JSON Messages
If a client sends malformed JSON, the server logs the raw message and an error:Error processing message: SyntaxError: Unexpected token ... Raw message that failed: <message>
This project is licensed under the MIT License. See the LICENSE file for details.
Contributions are welcome! Feel free to submit issues, feature requests, or pull requests.
For questions or support, please contact steve@saphirelabs.com.