【发布时间】:2014-11-01 15:25:24
【问题描述】:
我一直在使用 NodeJS 和 socket.io 来实现推送 api 和 filewatcher。
我看过这个例子: http://www.gianlucaguarini.com/blog/nodejs-and-a-simple-push-notification-server/
我启动并运行了服务器,当 XML 更改时,服务器将推送通知。 如果我转到 localhost:8000,我只会看到数据更改。如果我只是打开文件 node.html 它将保持空白并给出错误(在调试中)socket.io 无法找到(404)。
我做错了什么还是需要添加到代码中?
这是代码(server.js):
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
parser = new require('xml2json'),
fs = require('fs');
// creating the server ( localhost:8000 )
app.listen(8000);
// on server started we can load our client.html page
function handler(req, res) {
fs.readFile(__dirname + '/node.html', function(err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading node.html');
}
res.writeHead(200);
res.end(data);
});
}
// File watcher
io.sockets.on('connection', function(socket) {
console.log(__dirname);
// watching the xml file
fs.watch(__dirname + '/cache/file.xml', function(curr, prev) {
// on file change we can read the new xml
fs.readFile(__dirname + '/cache/file.xml', function(err, data) {
if (err) throw err;
// parsing the new xml data and converting them into json file
var json = parser.toJson(data);
// adding the time of the last update
json.time = new Date();
// send the new data to the client
socket.volatile.emit('file', json);
});
});
});
node.html
<html>
<head>
<!--
* Author: Gianluca Guarini
* Contact: gianluca.guarini@gmail.com
* Website: http://www.gianlucaguarini.com/
* Twitter: @gianlucaguarini
-->
<title>Push notification server</title>
</head>
<body>
<div id="file"></div>
<script src="socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
// creating a new websocket
var socket = io.connect('192.168.1.11:8000/');
// on every message recived we print the new datas inside the #container div
socket.on('file', function (data) {
// convert the json string into a valid javascript object
var data = JSON.parse(data);
$('#file').html(data);
});
</script>
</body>
</html>
【问题讨论】: