Skip to content

Commit

Permalink
fix: express and socket share same server
Browse files Browse the repository at this point in the history
  • Loading branch information
hhow09 committed Jan 22, 2025
1 parent 90bd4d1 commit 0d61fbc
Showing 1 changed file with 15 additions and 17 deletions.
32 changes: 15 additions & 17 deletions backend/src/chat-server.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,28 @@
import express, { Request, Response } from 'express';
import { Logger } from "pino";
import { Server, Socket } from "socket.io";
import { createServer } from "http";

export class ChatServer {
port: number;
app: express.Application;
logger: Logger;
io: Server;

constructor(logger: Logger, port: number = 3000) {
this.port = port;
this.logger = logger;
this.app = express();
// ref: https://socket.io/docs/v4/server-initialization/#with-express
this.io = new Server(createServer(this.app), {
cors: {
origin: '*',
}
});
this.setupAppRoutes();
this.setupSocketHandler();
}
setupAppRoutes() {
private setupAppRoutes() {
// health check
// ref: https://kubernetes.io/docs/reference/using-api/health-checks/
this.app.get('/livez', (req: Request, res: Response) => {
res.send('OK');
});
}

setupSocketHandler() {
this.io.on("listening", () => {
this.logger.info(`Server running at http://localhost:${this.port}`);
});
this.io.on('connection', (socket: Socket) => {
private setupSocketHandler(io: Server) {
io.on('connection', (socket: Socket) => {
const sessionLogger = this.logger.child({ session: socket.id });
sessionLogger.info(`Connected client session ${socket.id} on port ${this.port}`);
socket.on('disconnect', () => {
Expand All @@ -43,7 +31,17 @@ export class ChatServer {
});
}

listen() {
this.io.listen(this.port);
public listen() {
const httpServer = this.app.listen(this.port,
() => { console.log(`Server listening on port ${this.port}`) }
);

// Express server and socket.io server is sharing the same http server
const io = new Server(httpServer, {
cors: {
origin: '*',
}
});
this.setupSocketHandler(io);
}
}

0 comments on commit 0d61fbc

Please sign in to comment.