从节点中的rest api调用socket.io [英] Calling socket.io from rest api in node

查看:51
本文介绍了从节点中的rest api调用socket.io的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的 restful api 发出 socket.io 事件.

I am trying to emit a socket.io event from my restful api.

我当前的设置如下所示:

My current setup looks something like this:

app.js设置一个 express 应用并创建所有必要的路由,例如:

app.js setups an express app and creates all the necessary routes like:

var app = express();
...
var routesApi = require('./app_api/routes/index');
app.use('/api', routesApi);
module.exports = app;

server.js创建一个服务器并连接 express 应用程序和 socket.io

server.js creates a server and hooks up both express app and socket.io

var http = require('http');
var server = http.createServer(app);

require('../app_server/controllers/socket.js').socketServer(server);

一切正常,我可以成功地从客户端触发套接字事件,在 socket.js 中处理它并发出结果.

Everything works and I can successfully fire a socket event from the client, process it inside socket.js and emit the results.

然而,我想要做的是从我的restful api调用socket.js方法,我不知道如何连接它.

However, what I am trying to do is call socket.js method from my restful api and I can't figure out how to hook that up.

由于套接字服务器是在 server.js 中初始化的,而我的 api 路由是在 app.js 中连接的,我不确定让它们相互通信的正确方法是什么.

Since socket server is initialized inside server.js and my api routing is hooked up in app.js, I am not sure what's the proper way of getting them to talk to each other.

谢谢

推荐答案

你应该在 express 部分(或者你有 app 的地方)初始化 Socket.io,这样你就可以将它保存在 express 请求中并在您想要的每条路线中使用它.

You should initialise Socket.io inside the express section (or where you have app) so you can save it inside the express request and use it in every route you want.

因此,在您的 app.js 中,您创建了套接字,然后将其保存在 app 中:

So in your app.js you create the socket and then you save it in app:

var socketIo =  require('../app_server/controllers/socket.js').socketServer(server); // Make sure this returns the socketio

app.set('socketIo', socketIo);

现在,您可以在每条路线中执行此操作:

Now in every route you can do this:

app.route('/test').get(function (req, res) {
   var socket = req.app.get('socketIo');
   socket.emit('hello', 'world');
   res.end();
}

这篇关于从节点中的rest api调用socket.io的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆