Socket.io 在 Express Route 上发出 [英] Socket.io emit on Express Route

查看:28
本文介绍了Socket.io 在 Express Route 上发出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在调用某个 API 路由时向客户端发送一些数据.我必须遵循 server.js 上的代码

I want to emit some data to the client when some API route gets called. I have to following code on server.js

var app  = express();
var http = require('http').Server(app);

var io   = require('socket.io')(http);

io.on('connection', function(socket){
  console.log('a user connected');

  socket.emit('tx', 'msg');

  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

现在我有了这条路线/test:

Now I have this route /test:

var bsg   = require('./routes/test');

那个文件:

var express      = require('express');
var passport     = require('passport');
var router       = express.Router();

router.get('/test',  function(req, res) {
  //work here
});

module.exports = router;

在客户端:

<script type="text/javascript">
   var socket = io();

   socket.on('tx', function(data) {
     console.log(data);
   });
</script>

对此的最佳解决方案是什么?

Whats the best solution for this?

谢谢!

Express 4/socket.io 1.4.5

Express 4 / socket.io 1.4.5

推荐答案

io 实例附加到您的应用程序.

Attach the io instance to your app.

app.io = io;

然后您可以通过请求访问它.

Then you can access it via the request.

router.get('/test',  function(req, res) {
  req.app.io.emit('tx', {key:"value"});
});

我应该注意到越正确"的将数据附加到表达的方法是使用 app.set('io', io)app.get('io') 来检索它,以防 express 开始使用 io 属性来做某事.

I should note that the more "correct" way to attach data to express is using app.set('io', io) and app.get('io') to retrieve it, just in case express started using the io property for something.

如果您希望向单个客户端发送数据,则需要保留某种会话映射以将独立的 http 请求链接到套接字.会话 ID 可能不是一对一的映射,因为您可以为一个会话打开多个套接字.最好直接使用 socket.io 回调处理请求/响应模式.

If you are expecting to emit data to a single client you would need keep some kind of session mapping to link a standalone http request to a socket. A session ID might not be a one to one mapping though as you can have many sockets open for one session. You are better off handling a request/response pattern directly with socket.io callbacks.

这篇关于Socket.io 在 Express Route 上发出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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