import { Server } from 'socket.io'; const io = new Server(3000); io.on('connection', (socket) => { socket.emit('welcome', 'Hello client!'); });
When a client connects, the server triggers the 'connection' event. Inside, it sends a 'welcome' message only to that client using socket.emit.
import { io } from 'socket.io-client'; const socket = io('http://localhost:3000'); socket.on('welcome', (msg) => { console.log(msg); });
The client listens for the 'welcome' event and logs the message sent by the server. The URL includes the port 3000, matching the server.
The correct way to enable CORS for all origins is to set cors: { origin: '*' }. Other options are invalid or incorrect property names.
The client listens for 'message' events but the server emits 'msg'. Event names must match exactly for communication.
Socket.io provides extra features like automatic reconnection, fallback to other protocols if WebSocket is unavailable, and easy event-based communication. This simplifies building real-time apps.
