Php 套接字IO从URL获取数据

Php 套接字IO从URL获取数据,php,node.js,broadcast,socket.io,Php,Node.js,Broadcast,Socket.io,您好 我试图根据从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

您好

我试图根据从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(){ … }) 

});
var http=require('http'),
io=require('socket.io'),
//我这里还需要别的吗?
server=http.createServer(函数(req,res){
//您的正常服务器代码
res.writeHead(200,{'Content-Type':'text/html'});
//res.end(“你好,世界”);
});
监听服务器(8080);
//socket.io
var socket=io.listen(服务器);
socket.on('connection',函数(客户端){
//我不确定从哪里/如何从URL获取数据
函数getMessages(){
var request=messageClient.request(“GET”,“json.php”,“host”:“myurl.com”});
//这就是我向客户发送数据的方式吗?
套接字。广播(请求);
//request.end();
}
设置间隔(getMessages,1000);
on('message',function(){…})
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> 
//也加载jQuery
var socket=new io.socket({node\u server\u url});
socket.connect();
on('connect',function(){…})
socket.on('message',函数(数据){
//在这里使用jquery处理json数据并向客户端显示消息
//只要“数据”是json,我就可以处理这部分
}) 
socket.on('disconnect',function(){…})

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));
        });
    });
}