【问题标题】:Socket.io across different Node.js routes跨不同 Node.js 路由的 Socket.io
【发布时间】:2015-07-21 11:14:46
【问题描述】:

我正在构建使用 Express 框架和 Socket.io 的简单 Node.js 应用程序。我被卡住了,但是试图通过不同的快速路由从服务器接收消息。有没有办法通过服务器接收从一条路由发送到另一条路由的消息?我在下面给出了一个非常简化的代码版本:

app.js

var express = require("express"),
    app = express(),
    http = require("http").createServer(app),
    fs = require("fs"),
    io = require("socket.io").listen(http);

//Create a server
var port = 9001;
http.listen(port, function() {
  console.log("Server is running on port " + port);
});

//Set up routes
var anotherPage = express.Router();
anotherPage.route('/')
.get(function(req, res, next) {
  res.sendFile('/AnotherPage.html', {root: './public'});
});
var someOtherPage = express.Router();
someOtherPage.route('/')
.get(function(req, res, next) {
  res.sendFile('/SomeOtherPage.html', {root: './public'});
});

//Set up static directories
app.use(express.static(__dirname + "/public"))
    .use('/anotherpage', anotherPage)
    .use('/someotherpage', someOtherPage);

io.sockets.on("connection", function(socket) {
  socket.on("send message", function(data) {
    socket.emit('return message', data);
  });
});

在公用文件夹内

AnotherPage.html

<!DOCTYPE html>
<html>
<head>
  <title>Sender</title>
  <script type="text/javascript" src="/socket.io/socket.io.js"></script>
  <script src="/anotherPage.js"></script>
</head>
<body>
  <input id="input" type="text" />
  <button onclick="sendMessage()">Submit</button>
</body>
</html>

anotherPage.js

var socket = io.connect();

function sendMessage() {
  socket.emit("send message", document.getElementById('input').value );
}

socket.on('return message', function(data){
  //Working
  console.log(data);
});

SomeOtherPage.html

<!DOCTYPE html>
<html>
<head>
  <title>Receiver</title>
  <script type="text/javascript" src="/socket.io/socket.io.js"></script>
  <script src="/someOtherPage.js"></script>
</head>
<body>
  //TODO
</body>
</html>

someOtherPage.js

var socket = io.connect();

socket.on('return message', function(data){
  //Not working
  console.log(data);
});

【问题讨论】:

  • 您到底想达到什么目的?如果用户在浏览器中加载了anotherPage并单击按钮,则客户端将send message发送给IO,IO将return message发送回同一个客户端。 someOtherPage此时甚至没有加载,它如何接收return message
  • 假设两者都已加载。
  • 如何加载它们?您是指不同的客户(或在不同的选项卡中,针对不同客户的所有意图和目的)?再说一遍,你到底想达到什么目标?
  • 是本质上不同的客户。再次澄清一下,基本上让 AnotherPage.js 使用 socket.io 发送消息,然后 SomeOtherPage.js 能够使用 socket.io 从不同的路由接收消息。

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


【解决方案1】:

正如我在评论中所说,服务器上的socket.emit 只会将return message 发送给一个客户端,与它收到的send message 相同。如果您想发送给任何收听的人,请改用io.sockets.emit;或除socketsocket.broadcast.emit 之外的所有人。

基本上,您想知道为什么其他人无法窃听私人谈话。 :) 它与 Express 路由无关,与 socket.io API 有关。

【讨论】:

  • 是的,谢谢你这么简单socket.broadcast.emit 正是我想要的。您将如何包含发件人?
  • 发件人姓名,只要在邮件中包含任何字符串。如果您的意思是发送消息的ID,那就是socket.id;您可以使用 IIRC、io.clients[id].emit 从服务器发送到特定客户端。
猜你喜欢
  • 1970-01-01
  • 2019-05-28
  • 1970-01-01
  • 1970-01-01
  • 2021-05-14
  • 2017-06-29
  • 1970-01-01
  • 2018-01-26
  • 1970-01-01
相关资源
最近更新 更多