import io from "socket.io-client";
const newSocket = io("http://localhost:5000"); // Connect to socket.io server
Minimal setup
const socketIo = require("socket.io")(5000);
io.on("connection", socket => {
console.log(socket);
})
Setup with express server and http
const express = require("express");
const socketIo = require("socket.io");
const cors = require("cors");
const http = require("http");
const app = express();
const server = http.createServer(app); // Integrate express app with the http-server
const io = socketIo(server, {
cors: {
origin: "http://localhost:5173",
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
console.log("A user connected:", socket.id);
socket.on("disconnect", () => {
console.log("A user disconnected:", socket.id);
});
});
Listening to events (name is free to choose, listening and emitting name has to match)
socket.on("name", callback)
Emitting events
socket.emit("name", data)
Broadcast Messages (Sends a message or event to all connected clients except the sender)
socket.broadcast.emit("name", data)
Join Rooms (Clients in the same room can receive events targeted specifically to that room.)
socket.join("room name")
Room Broadcasts (Sends an event to all clients in a specific room, including the sender if they are part of the room.)
io.to("room name").emit("name", data)