Socket.io在Express Route上发出

时间:2022-08-22 15:26:52

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

我想在调用某些API路由时向客户端发出一些数据。我必须在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');
  });
});

Now I have this route /test:

现在我有这条路线/测试:

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

And that file:

那个档案:

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

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

module.exports = router;

On client side:

在客户端:

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

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

Whats the best solution for this?

什么是最好的解决方案?

Thanks!

Express 4 / socket.io 1.4.5

Express 4 / socket.io 1.4.5

2 个解决方案

#1


29  

Attach the io instance to your app.

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

app.io = io;

Then you can access it via the request.

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

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

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.

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

#2


2  

You can attach the instance to req object also:

您还可以将实例附加到req对象:

app.use(function(req,res,next){
req.io = io;
next();
})

And to emit to a single client

并向一个客户发射

req.io.to(<socketId of cient>).emit(data);

#1


29  

Attach the io instance to your app.

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

app.io = io;

Then you can access it via the request.

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

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

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.

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

#2


2  

You can attach the instance to req object also:

您还可以将实例附加到req对象:

app.use(function(req,res,next){
req.io = io;
next();
})

And to emit to a single client

并向一个客户发射

req.io.to(<socketId of cient>).emit(data);