Socket.IO Quick Reference
Server Side
npm install socket.io
You need to explicitly enable Cross-Origin Resource Sharing
import { Server } from 'socket.io';
import http from 'http';
const server = http.createServer(app); // Create an HTTP server instance
const io = new Server(server, { // Create a Socket.IO server instance
cors: {
origin: ['http://localhost:4200', 'https://example.com'],
methods: ['GET', 'POST'],
},
});
Emitting events
io.on('connection', (socket) => {
socket.emit('fish', 'This is the fish event');
});
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
});
});
io.on('connection', (socket) => { socket.emit('fish', 'This is the fish event'); socket.emit('message', 'This is the message event'); socket.on('message', (msg) => { console.log('message: ' + msg); }); });
Client Side
npm install socket.io-client