【发布时间】:2014-10-08 13:18:09
【问题描述】:
我有一个现有的 socket.io 应用程序来更新页面,有人写了一条消息,它出现在连接到套接字的所有客户端上。这部分工作正常。
我需要每分钟读取一个 json 提要并将提要中的数据发送到同一系统,基本上我正在尝试将辅助发件人添加到系统中。 (稍后我会将“feed reading”部分放入无限循环)代码如下:
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);
});
当我运行脚本时,我得到了:
var socket = io.connect('http://host_url.com:8000'); ^ TypeError: Object # has no method 'connect' 在对象。 (索引 x.js:4:17) 在 Module._compile (module.js:456:26) 在 Object.Module._extensions..js (module.js:474:10) 在 Module.load (module.js:356:32) 在 Function.Module._load (module.js:312:12) 在 Function.Module.runMain (module.js:497:10) 启动时 (node.js:119:16) 在 node.js:902:3
我从“消息表单”页面导出代码,它运行良好:
<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>
消息表单、宿主应用程序和这个提要阅读器在同一个文件夹中,所以它使用同一个 socket.io 库。
有什么建议吗?
【问题讨论】: