-
Notifications
You must be signed in to change notification settings - Fork 272
/
Copy pathsocket.js
38 lines (29 loc) · 1 KB
/
socket.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { Server } from "socket.io";
import http from "http";
import express from "express";
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: ["http://localhost:3000"],
methods: ["GET", "POST"],
},
});
export const getReceiverSocketId = (receiverId) => {
return userSocketMap[receiverId];
};
const userSocketMap = {}; // {userId: socketId}
io.on("connection", (socket) => {
console.log("a user connected", socket.id);
const userId = socket.handshake.query.userId;
if (userId != "undefined") userSocketMap[userId] = socket.id;
// io.emit() is used to send events to all the connected clients
io.emit("getOnlineUsers", Object.keys(userSocketMap));
// socket.on() is used to listen to the events. can be used both on client and server side
socket.on("disconnect", () => {
console.log("user disconnected", socket.id);
delete userSocketMap[userId];
io.emit("getOnlineUsers", Object.keys(userSocketMap));
});
});
export { app, io, server };