简体   繁体   English

每个请求的ExpressJS / Node / Socket.io广播消息

[英]ExpressJS/Node/Socket.io Broadcast Message on every request

I have a nodejs application in which I want to monitor every incoming request live on a webpage. 我有一个nodejs应用程序,我想在其中监视生活在网页上的每个传入请求。 I am trying to do this using socket.io. 我正在尝试使用socket.io。 I have the following in my app.js file 我的app.js文件中包含以下内容

var express = require('express');
var http = require('http');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);

var usageLogger = function(req, res, next) {
    console.log("GOT REQUEST !");
    var os = require("os"),
    cpus = os.cpus();

    var url = "URL: " + req.url + "\n" ;
    var urlTime = "Time: " + new Date().getTime() + "\n" ;

    var liveMessage = "<div><p><b>URL:</b> "+ req.url + "</p><p><b>Time: </b> " + new Date().getTime() + "</p></div>"

    io.on('connection', function(socket){
      socket.emit('news', liveMessage);
    });
}

app.use(usageLogger);

In my footer.jade file , I have the following: 在我的footer.jade文件中,我具有以下内容:

.container
    .footer
        hr(style='margin: 30px 0 10px 0;')
        p &copy;&nbsp;
            a(href='#') Author
            |  2014

script(src='/javascripts/bootstrap.min.js')
script(src="/socket.io/socket.io.js")
script(type='text/javascript')
  |var socket = io();
  |socket.on('news', function(msg){
  |$('#messages').append(msg);
  |});


block footer

When I access any page, i only get the broadcast message, when i refresh the index page of the site. 当我访问任何页面时,当我刷新站点的索引页面时,我只会收到广播消息。 So for example, when I first access localhost:300, i can see the following: 因此,例如,当我第一次访问localhost:300时,我可以看到以下内容:

URL: / time: 0909234234 网址:/时间:0909234234

However, if I open a new tab and access localhost:3000/example, i have to refresh the first page to get the following view 但是,如果我打开一个新选项卡并访问localhost:3000 / example,则必须刷新第一页才能获得以下视图

URL: / time: 0909234234 网址:/时间:0909234234

URL: /example time: 0909234239 网址:/ example时间:0909234239

I am struggling to see why this does not automatically update without having to refresh the page. 我正在努力查看为什么在不刷新页面的情况下无法自动更新的原因。 Any help me greatly appreciated. 任何帮助我都非常感激。

in your code, for each coming request, when a socket connects, you emit news to that socket. 在您的代码中,对于每个即将到来的请求,当套接字连接时,您都会向该套接字发出news what you want is, when a request comes in, emit news to all connected sockets. 您想要的是,当有请求进入时,向所有连接的套接字发出news you can do it in this way : 您可以通过以下方式进行操作:

var usageLogger = function(req, res, next) {
   //do what you want
   ...
   io.sockets.emit('news', liveMessage);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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