gpt4 book ai didi

node.js - 使用 inversify-express-utils,我如何集成 websocket?

转载 作者:太空宇宙 更新时间:2023-11-03 22:46:08 25 4
gpt4 key购买 nike

我们尝试使用 websockets 连接以扩展基于 inversify-express-utilstypescript 应用程序,但到目前为止还没有成功:

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。有什么想法吗?

最佳答案

我前段时间也遇到过类似的问题。这是对我有用的:

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 变量还不够。我希望这对您有用。

最诚挚的问候
....西蒙

关于node.js - 使用 inversify-express-utils,我如何集成 websocket?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40612963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com