0
我試圖根據從URL獲得的數據向用戶廣播消息。從URL返回的數據將是json。我對node.js和socket.io非常陌生,並且安裝了node.js和socket.io。我只是不能100%確定如何獲取我需要通過URL向客戶端廣播的數據。我還需要其他什麼?
我的服務器上的文件server.js
var http = require('http'),
io = require('socket.io'),
// Do I need another require here?
server = http.createServer(function(req, res){
// your normal server code
res.writeHead(200, {'Content-Type': 'text/html'});
//res.end('<h1>Hello world</h1>');
});
server.listen(8080);
// socket.io
var socket = io.listen(server);
socket.on('connection', function(client){
//I'm not sure where/how to get data from a URL
function getMessages() {
var request = messageClient.request("GET", "json.php", {"host": "myurl.com"});
// Is this how I send the data to the client?
socket.broadcast(request);
//request.end();
}
setInterval(getMessages, 1000);
client.on('message', function(){ … })
client.on('disconnect', function(){ … })
});
我的客戶
// Load jQuery too
<script src="http://pathtojquery.js"></script>
<script src="http://{node_server_url}/socket.io/socket.io.js"></script>
<script>
var socket = new io.Socket({node_server_url});
socket.connect();
socket.on('connect', function(){ … })
socket.on('message', function(data){
// Use jquery to handle the json data here and display message to the clients
// I can handle this part as long as 'data' is json
})
socket.on('disconnect', function(){ … })
</script>