简体   繁体   中英

Socket.io across different Node.js routes

I am building simple Node.js application that uses the Express Framework as well as Socket.io. I got stuck however trying to receive messages from the server across different express routes. Is there a way of receiving messages sent from one route to another route through the server? I've given a very simplified version of my code below:

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);
  });
});

Inside public folder

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);
});

As I said in the comment, socket.emit on the server will send return message only to the one client, the same that it received send message from. If you want to send to anyone listening, use io.sockets.emit instead; or to all except socket with socket.broadcast.emit .

Basically, you are wondering why someone else can't eavesdrop on a private conversation. :) It has nothing to do with Express routing, and everything to do with socket.io API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM