// Import 'ws' module
const WebSocket = require('ws');
// Create WebSocket Server on port 8080
const wss = new WebSocket.Server({ port: 8080 });
// Event listener for new connections
wss.on('connection', (ws) => {
// Event listener for incoming messages
ws.on('message', (message) => {
console.log('Received:', message);
// Send a response back to the client
ws.send('Server: ' + message);
});
});Simple WebSocket Server using 'ws' library
javascript
Related Posts
More content you might like
Tutorial
Build a Custom Rate Limiter in Node.js with Redis
When developing web apps or APIs, it’s critical to prevent users from overwhelming your server. That’s where rate limiting comes in. In this guide, we’ll build a custom rate limiter in Node.js using Redis—no libraries, no magic, just code you control and understand.
- How to use Redis to count and throttle requests
- How to implement reusable middleware in Express
- How to rate limit by IP or API key
- Why this method is better for learning and customization
Apr 04, 2025
Read More Tutorial
python
Build a Multiplayer Game with Python and WebSockets
import asyncio
import websockets
import json
game = TicTacToe()
players = []
async def handler(websocket, path):
global players
players.append(websocket)
try:
async for message in websocket:
data = json.loads(message)
if "move" in data:
position = data["move"]
response = game.make_move(position)
for player in players:
await player.send(json.dumps({"board": game.board, "status": response}))
except websockets.ConnectionClosed:
players.remove(websocket)
start_server = websockets.serve(handler, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()Serve the game interface using Flask.
Dec 10, 2024
Read More Tutorial
bash
How to Reset the MySQL Root Password Using DROP USER
- If you can't start MySQL after removing
skip-grant-tables, double-check the configuration file (mysqld.cnf) for typos or errors. - Make sure MySQL is running by checking its status:
sudo systemctl status mysqlOct 03, 2024
Read More Code
bash
How to view free space on a Linux server
df -h /home- Inodes: To check free inodes instead of disk space, use the
-ioption:
Aug 11, 2024
Read MoreDiscussion 0
Please sign in to join the discussion.
No comments yet. Be the first to share your thoughts!