【问题标题】:Send a message to the connected user using socket.io使用 socket.io 向连接的用户发送消息
【发布时间】:2017-06-22 15:26:50
【问题描述】:

我很难理解如何使用socket.io 向执行 HTML 请求的用户发送消息。

更多解释:

服务器

我的服务器是expressJS,我使用router.getrouter.post 来管理我的所有应用程序。 我也使用 cookie-session (https://github.com/expressjs/cookie-session)。

客户

客户端必须先登录,然后他被重定向到一个单页应用程序,一切都由 AJAX 处理。

实时通知

我想让客户端做一个AJAX请求为例,并使用socket.io发送通知。

服务器端代码

  • app.js

// Require all modules first, then:
var server = https.createServer(options, app);
server.listen(443);
io = io().listen(server, {
  wsEngine: 'ws',     // Use "ws" engine (otherwise: seg. fault)
  pingInterval: 3000, // Time in ms to send a ping paquet
  pingTimeout: 3000,  // Time ins ms to set a connection as disconnected
  allowUpgrades: false,
  cookie: false
});
app.use(function (req, res, next) {
  if (!req.io) req.io = io;
  if (!req.sockets) req.sockets = {};
  next();
});
  • 索引路由 (index.js)

router.get('/home', function (req, res, next) {
  req.io.emit('logged', 'Hello!');

  // Some data processing
  // ...
  //
  
  res.render('home/home', { datas: datas, csrfToken: req.csrfToken() });
});

客户端代码

  • 索引页

<html>

<!-- page content -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script>
  // Import socket.io functions
  var socket = io.connect({
    reconnection: true,
    reconnectionDelay: 1000,
    reconnectionDelayMax: 5000,
    reconnectionAttempts: Infinity
  });
</script>
<script src="/static/js/socket.io-management.js"></script>

</html>
  • socket.io-management.js

socket.on('connect', function () {
  console.log('socket connected');
});
socket.on('disconnect', function () {
  console.log('socket disconnected');
});
socket.on('error', function () {
  console.log('socket error');
});

socket.on('logged', function (msg) {
  if ((msg !== 'undefined') && (msg !== null)) console.log(msg);
  else console.log('Logged');
});

问题

在服务器上,req.io.emit('logged', 'Hello!'); 正在工作,但将此消息发送给所有用户,而不是请求页面的用户。

如何仅将此消息发送给该特定用户?到目前为止,我已经尝试了很多东西,但都没有成功。

【问题讨论】:

    标签: javascript node.js sockets express socket.io


    【解决方案1】:

    您可以使用socketId发送给特定用户

    req.io.sockets.connected[socketid].emit('logged', 'Hello!');
    

    【讨论】:

    • 我试过了,但我需要为每个用户获取正确的套接字 id,但我没有成功
    猜你喜欢
    • 2019-08-04
    • 2020-09-10
    • 2018-01-14
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 2021-04-10
    • 2014-08-14
    • 1970-01-01
    相关资源
    最近更新 更多