Skip to content

Commit

Permalink
[#152] feat: 이용자 수 구독 로직 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
domino8788 committed Dec 20, 2020
1 parent 2f35584 commit bd9eb00
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions backend/src/socket.ts
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit bd9eb00

Please sign in to comment.