使用inversify-express-utils,如何集成websockets?

时间:2016-11-15 14:56:50

标签: node.js express typescript socket.io inversifyjs

我们尝试使用 websockets 连接基于 inversify-express-utils 扩展我们的 typescript 应用程序,但到目前为止没有运气:< / p>

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'));

服务器按预期启动ts-node server.ts。 但我无法连接到此网络套接字。尝试使用多种工具,例如Dark WebSocket Terminal chrome插件和执行\connect localhost:3000。 有什么想法吗?

3 个答案:

答案 0 :(得分:3)

我前段时间遇到过类似问题。以下是对我有用的内容:

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;

如您所见,您必须先创建Express服务器的运行实例,然后才能将Socket.IO附加到它上面。您的server变量不够用。我希望这对你有用。

最好的问候 ......西蒙

答案 1 :(得分:2)

可以在https://github.com/dkellenb/inversify-express-utils-websockets上找到一个工作示例。问题是:

  • 需要围绕应用
  • 创建服务器包装器
  • 应该在快速服务器上启动侦听
  • 测试连接字符串应如下所示:
    ws://localhost:3000/socket.io/?EIO=3&transport=websocket

代码段:

// server.build() actually returns an Express.Application instance
let app = server.build();

// socket.io expects an http.Server versus a InversifyExpressServer
// see http://socket.io/docs/#using-with-express-3/4
let httpServer = require('http').createServer(app);
httpServer.listen(3000);

// create socket.io
let io = socketIo(httpServer);

答案 2 :(得分:0)

import * as express from 'express';
import * as expressWs from 'express-ws';
import { InversifyExpressServer } from 'inversify-express-utils';
import { container } from "./utils/InversifyConfig";

let inversifyExpressServer = new InversifyExpressServer(container);
  inversifyExpressServer.setConfig((app: expressWs.Application) => {
     expressWs(app);
     // Your other config
  });