ソケットIO URLからデータを取得します
質問
ご挨拶、
URLから得られるデータに基づいて、ユーザーにメッセージをブロードキャストしようとしています。 URLから返されるデータはJSONです。私はnode.jsとsocket.ioを非常に初めて使用し、node.jsとsocket.ioがインストールされています。 URLを介してクライアントにブロードキャストするために必要なデータを取得する方法について100%確信がありません。他に何が必要ですか?
私のサーバーファイル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>
解決
function getMessages() {
http.get({ host: 'myurl.com', port: 80, path: 'json.php' }, function(response) {
var data = "";
response.on('data', function(chunk) {
data += chunk;
});
response.on('end', function() {
socket.broadcast(JSON.parse(data));
});
});
}
所属していません StackOverflow