< Node.js

Socket.IO

Szerző: Sallai András

Copyright © 2025, Sallai András

Licenc: CC BY-SA 4.0

Web: https://szit.hu

Szerver egyszerűen

npm install socket.io

const http = require('http'); const { Server } = require('socket.io'); const server = http.createServer(); const io = new Server(server); const PORT = 3000; // Socket.io események kezelése io.on('connection', (socket) => { console.log('A user connected'); socket.on('disconnect', () => { console.log('User disconnected'); }); socket.on('chat message', (msg) => { console.log(`Message: ${msg}`); }); }); // Szerver indítása server.listen(PORT, () => { console.log(`Listening on: ${PORT}`); });
{ "name": "pokerserver", "version": "0.0.1", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node app", "dev": "nodemon app --watch app" }, "keywords": [], "author": "", "license": "ISC", "description": "", "dependencies": { "socket.io": "^4.8.1" }, "devDependencies": { "nodemon": "^3.1.9" } }

Szerver Express mellett

const express = require('express'); const morgan = require('morgan'); const http = require('http'); const app = express(); const { Server } = require('socket.io'); app.use(morgan('dev')); const server = http.createServer(app); const io = new Server(server); io.on('connection', (socket) => { console.log('A user connected'); socket.on('disconnect', () => { console.log('User disconnected'); }); socket.on('chat message', (msg) => { console.log(`Message: ${msg}`); }); }); server.listen(3000, () => { console.log('Server is running on port 3000'); });