在Node.js中如何从处理程序/回调方法向客户端发送消息

时间:2015-01-29 15:15:38

标签: node.js express socket.io pkgcloud

我是node.js的初学者。我正在尝试使用node.js创建一个webapp,它将在云中创建服务器并对其进行管理。在做了一些研究后,我决定使用node.js,socket.io,express和pkgcloud模块来创建webapp。现在,我面临的问题是,当创建服务器时,我无法向前端/客户端发送消息。服务器已成功创建,但我没有得到如何将服务器状态发送到浏览器屏幕。

这是代码: index.js

var express = require('express'),
app = express();

app.use(express.static(__dirname + '/'));

var io = require('socket.io').listen(app.listen(1337));

io.sockets.on('connection', function(socket) {
    socket.on('mesg_to_server', function(data) {

       // This is for testing whether we're receiving msgs on client side
       io.sockets.emit("mesg_to_client",{ mesg: data["mesg"], mesg1: data["mesg1"] });

       var Rackspace = require('./ex_rackspace');
       var rackspace = new Rackspace();
       rackspace.create(data.mesg);
   });
}); 

ex_rackspace.js:

  var pkgcloud = require('pkgcloud'),
  _ = require('./node_modules/pkgcloud/node_modules/underscore');

  var client = pkgcloud.providers.rackspace.compute.createClient({
                 username: 'xxxx',
                 apiKey: 'xxxxx',
                 region: 'HKG'
              });

  // This function will handle our server creation,
  // as well as waiting for the server to come online after we've
  // created it.
  function handleServerResponse(err, server) {
     if (err) {
       console.dir(err);
       return;
     }

     console.log('SERVER CREATED: ' + server.name + ', waiting for active status');

     // Wait for status: ACTIVE on our server, and then callback
     server.setWait({ status: server.STATUS.running }, 5000, function (err) {
      if (err) {
        console.dir(err);
        return;
      }

      console.log('SERVER INFO');
      console.log(server.name);
      console.log(server.status);
      console.log(server.id);

      console.log('Make sure you DELETE server: ' + server.id +
  ' in order to not accrue billing charges');
  });
  }

  var Rackspace = function() {

  };  

  Rackspace.prototype.test = function (text) {
     console.log("provider: Rackspace: " + text);
  }       

  // first we're going to get our flavors
  Rackspace.prototype.create = function (server) {
     client.getFlavors(function (err, flavors) {
     if (err) {
       console.dir(err);
       return;
     }

     // then get our base images
     client.getImages(function (err, images) {
       if (err) {
         console.dir(err);
         return;
       }

       var flavor = _.findWhere(flavors, { name: '1 GB Performance' });

       var image = _.findWhere(images, { name: 'CentOS 5 (PV)' });

       // Create our first server
       client.createServer({
          name: server,
          image: image,
          flavor: flavor
       }, handleServerResponse);
     });
   });
  }

  module.exports = Rackspace;

page.html(客户端):

<!DOCTYPE html>
<html>
  <head>
    <script src="/socket.io/socket.io.js"></script>
    <script type="text/javascript">
        // our socket.io code goes here
        var socketio = io.connect("127.0.0.1:1337");

        socketio.on("mesg_to_client", function(data) {
            document.getElementById("chatlog").innerHTML = ("<hr/>" +
            data.mesg + ' ' + data.mesg1 + document.getElementById("chatlog").innerHTML);
        });

        socketio.on("test_output", function(data) {
            console.log(data.mesg); 
        });

        function sendMessage() {
            var msg = document.getElementById("mesg_input").value;
            socketio.emit("mesg_to_server", { mesg : msg, mesg1 : "here"});
        }

    </script>
 </head>
 <body>
    <input type="text" id="mesg_input"/>
    <button onclick="sendMessage()">Create</button>
    <div id="chatlog"></div>
 </body>
</html>

1 个答案:

答案 0 :(得分:1)

您需要向create function添加回调

Rackspace.prototype.create = function (server, callback){
     //your code - if err send error else send success message
     callback(err, message)
}

然后在调用create

时使用它
rackspace.create(data.mesg, function (err, message){
     //your code with your socket emit here
});