Skip to content

How to initialize a socket.io Server on an already initialized Express App? #4256

Answered by darrachequesne
dennisat asked this question in Q&A
Discussion options

You must be logged in to vote

Your first example should work properly, as long as you use httpServer.listen() and not app.listen():

import * as express from "express";
import * as http from "http";
import { Server } from "socket.io";

const app = express.default();
const httpServer = http.createServer(app); // Where app is the initialized Express App
const wsServer = new Server(httpServer);

wsServer.on('connection', (socket) => {
  console.log('a user connected', {socket});
  socket.on('ccc', data => {
    console.log('message from client', data);
    socket.emit('server-message', 'gotcha');
  });
  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
});

httpServer.listen(3000);

Reference: ht…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@dennisat
Comment options

Answer selected by dennisat
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants