From bd9eb00cfb78c5a4d512a63ebc0177f40dafb8dd Mon Sep 17 00:00:00 2001 From: domino8788 Date: Sun, 20 Dec 2020 10:50:01 +0900 Subject: [PATCH] =?UTF-8?q?[#152]=20feat:=20=EC=9D=B4=EC=9A=A9=EC=9E=90=20?= =?UTF-8?q?=EC=88=98=20=EA=B5=AC=EB=8F=85=20=EB=A1=9C=EC=A7=81=20=EA=B5=AC?= =?UTF-8?q?=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/socket.ts | 55 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 backend/src/socket.ts diff --git a/backend/src/socket.ts b/backend/src/socket.ts new file mode 100644 index 0000000..aa7e394 --- /dev/null +++ b/backend/src/socket.ts @@ -0,0 +1,55 @@ +import { Application } from 'express'; +import http from 'http'; +import { Server, Socket } from 'socket.io'; + +const webSocket = (server: http.Server, app: Application, session: any) => { + const io = new Server(server, { path: '/socket.io' }); + + app.set('io', io); + const page = io.of('/page'); + const pageList = io.of('/pageList'); + + io.use((socket, next) => { + session(socket.request, {}, next); + }); + + pageList.on('connection', (socket: Socket) => { + const req = socket.request; + const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; + pageList.emit('allUserCount', pageList.sockets.size); + socket.on('disconnect', () => { + pageList.emit('allUserCount', pageList.sockets.size); + }); + }); + + page.on('connection', (socket: Socket) => { + const req = socket.request as any; + const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; + const leaveBeforeRoom = (socket: Socket) => { + socket.rooms.forEach((room) => { + socket.leave(room); + const clientsSize = (page.adapter as any).rooms.get(room)?.size; + page.to(room).emit('pageUserCount', clientsSize ?? 0); + }); + }; + leaveBeforeRoom(socket); + socket.on('disconnect', () => { + leaveBeforeRoom(socket); + }); + + socket.on('error', (error) => { + console.error(error); + leaveBeforeRoom(socket); + }); + + socket.on('join', (pageId) => { + leaveBeforeRoom(socket); + socket.join(pageId); + page + .to(pageId) + .emit('pageUserCount', (page.adapter as any).rooms.get(pageId).size); + }); + }); +}; + +export default webSocket;