【发布时间】: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