I have an existing socket.io app to update a page, someone writes a message and it appears on all the clients connected to the socket. This part works fine.
I need to read a json feed every minute and send the data in feed into same system, basically I am trying to add a secondary sender into system. (I will put 'feed reading' part into infinite loop later) Here is the code:
var http = require('http');
var server = require('http').Server();
var io = require('socket.io')(server);
var socket = io.connect('http://host_url.com:8000');
http.get('http://json_feed_url', function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var items = JSON.parse(body)
items.forEach(function(item, index) {
socket.emit('update', {
title: item.title,
message: item.message
});
});
});
}).on('error', function(e) {
console.log("Got error: ", e);
});
When I run the script I got:
var socket = io.connect('http://host_url.com:8000'); ^ TypeError: Object # has no method 'connect' at Object. (inde x.js:4:17) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:902:3
I derived the code from the 'message form' page and it works perfectly:
<script src="http://host_url.com:8000/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://host_url.com:8000');
function update_score() {
socket.emit('update', {
title: $("#txtTitle").val(),
message: $("#txtMessage").val()
});
}
</script>
The message form, the host app and this feed reader are in the same folder, so it uses the same socket.io library.
Any suggestion?
You need to use socket.io-client to simulte clients sending messages from a server.
Try:
var socket = require('socket.io-client')('http://localhost');
socket.on('connect', function(){
socket.on('event', function(data){});
socket.on('disconnect', function(){});
});
I found the issue after spending 2 days on it.
The host app was written 6+ months ago and I usually don't update the javascript libraries unless there is a problem/bug/new feature that I need.
So when I installed socket.io-client for this new additional module, it was a new version of the library.
The error was simply a version conflict between the client and the host. I upgraded socket.io version on the host app to latest and the code started to work.
I hope it helps others.