Search code examples
node.jsexpresstypescriptsocket.ioinversifyjs

Using inversify-express-utils, how can i integrate websockets?


We try to connect to extend our typescript application based on inversify-express-utils with websockets, but no luck so far:

import 'reflect-metadata';
import {interfaces, InversifyExpressServer, TYPE} from 'inversify-express-utils';
import { Kernel } from 'inversify';
import {UserController} from './controller/UserController';
import TYPES from './constant/types';
import * as socketIo from 'socket.io';

// set up kernel
let kernel = new Kernel();

// create server
let server = new InversifyExpressServer(kernel);
kernel.bind<interfaces.Controller>(TYPE.Controller).to(UserController).whenTargetNamed(TAGS.UserController);
server
  .build()
  .listen(3000, 'localhost', () => console.log('listening on http://localhost:3000'));

// try to setup a socket io based websocket
let io = socketIo(server);
io.on('connect', (socket) => console.log('"connect" executed'));
io.on('connection', (socket) => console.log('"connection" executed'));

Server starts up as expected with ts-node server.ts. But I can't connect to this web socket. Tried it with several tools, like for example Dark WebSocket Terminal chrome plugin and executing \connect localhost:3000. Any idea?


Solution

  • I've got some similar issue some time ago. Here is what was worked for me:

    let server: interfaces.InversifyExpressServer = new InversifyExpressServer(kernel);
    
    server.setConfig((app) => {
        ... 
        app.use(helmet());
        ...
    });
    
    let app = server.build();
    
    let instance: any = app.listen(config.url.port);
    console.log(`Server started on port ${config.url.port} :)`);
    
    
    let socketIO = SocketIO.listen(instance);
    socketIO.on('connection', (socket: SocketIO.Server) => {
        socket.emit('news', { hello: 'world' });
        socket.on('my other event', function (data: any) {
            console.log(data);
        });
    });
    
    exports = module.exports = app;
    

    As you can see, you have to create a running instance of your express server before you can attach Socket.IO on to it. Your server variable is not enough. I hope this will work for you.

    Best regards
    .... Simon