我正在构建使用Express Framework和Socket.io的简单Node.js应用程序。我遇到了困难,但试图通过不同的快速路线从服务器接收消息。有没有办法接收通过服务器从一条路由发送到另一条路由的消息?我在下面给出了一个非常简化的代码版本:
app.js
select * from a
where trunc(a.eff_dt) between trunc(to_date('01/01/2015','MM/DD/YYYY'))
and trunc(to_date('01/02/2015','MM/DD/YYYY'))
and br_type = 'ASD'
AnotherPage.html
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.js
<!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>
SomeOtherPage.html
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.js
<!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>
答案 0 :(得分:2)
正如我在评论中所说,服务器上的socket.emit
只会向一个客户端发送return message
,与收到send message
的客户端相同。如果您想发送给任何倾听的人,请改用io.sockets.emit
;或socket
除socket.broadcast.emit
以外的所有人。
基本上,你想知道别人为什么不能窃听私人谈话。 :)它与Express路由无关,而与socket.io
API有关。