I have a scenario where I have Node pulling data from one server through net.socket connection and then using sockets.io to output to a client browser. Data from the server updates roughtly every minute or so. If I output that data to the console it works fine, showing updates as they occur. However, I cannot seem to get that data to be pushed to browser by socket.io. I'm good with PHP but complete newbie to javascript. I do understand though that as data is updated from the server it should be triggering an "event" that causes socket.io to push new data out. I'd appreciate any help.
//set all variables and modules includes here
// [...]
server = http.createServer (function(req, res) {
res.writeHead(200, {'Content-Type:' 'text/html'});
res.end(index);
}).listen(8080, localhost);
//connection to stats server
var socket = new net.Socket();
socket.connect (6000, "xxx.xxx.xxx.xxx", function () {
console.log("connected");
});
socket.on('data', function(data) {
var buf = new Buffer(data, 'base64');
var calls = buf.toString();
console.log(calls); // if I include this, data outputs to console perfectly
//set up socket.io connection to client
var clientupdate = function clientupdate() {
io.sockets.on('connection', function(socket) {
socket.emit('calls', {data: calls});
});
}
});
You are not calling the clientupdate function. You declare it but you don't call. All you need is:
clientupdate();
There are a couple of issues with the code:
clientUpdate
function is never called, so the server doesn't respond to new clients at all. io
object instead, this will send the message to all connected clients. Combined this would look something like this (untested, but it should work):
//set all variables and modules includes here
// [...]
server = http.createServer (function(req, res) {
res.writeHead(200, {'Content-Type:' 'text/html'});
res.end(index);
}).listen(8080, localhost);
//connection to stats server
var socket = new net.Socket();
socket.connect (6000, "xxx.xxx.xxx.xxx", function () {
console.log("connected");
});
socket.on('data', function(data) {
var buf = new Buffer(data, 'base64');
var calls = buf.toString();
console.log(calls);
//any data we have we emit to all the clients
io.emit('calls', { data : calls });
});
Note that since the individual connections are never used I omitted the entire io.on('connection')
part. It's only needed when you need to interact with individual clients.
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.