I have a nodejs application in which I want to monitor every incoming request live on a webpage. I am trying to do this using socket.io. I have the following in my app.js file
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:
.container
.footer
hr(style='margin: 30px 0 10px 0;')
p ©
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:
URL: / time: 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
URL: / time: 0909234234
URL: /example time: 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. what you want is, when a request comes in, emit news
to all connected sockets. you can do it in this way :
var usageLogger = function(req, res, next) {
//do what you want
...
io.sockets.emit('news', liveMessage);
}
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.