【问题标题】:Socket IO get data from URLSocket IO 从 URL 获取数据
【发布时间】:2011-08-14 18:50:15
【问题描述】:

您好,

我正在尝试根据从 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> 

【问题讨论】:

    标签: php node.js broadcast socket.io


    【解决方案1】:
    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));
            });
        });
    }
    

    HTTP module documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      • 2021-04-16
      • 2020-07-21
      • 2019-06-19
      • 2015-09-05
      • 1970-01-01
      • 2013-01-15
      相关资源
      最近更新 更多