Node.js和sockets.io;发射不起作用

时间:2013-09-03 13:53:59

标签: node.js sockets

我有这段代码:

服务器(使用http.Server):

var io = require("socket.io").listen(server);

io.sockets.on("connection", function (socket) {
    socket.emit("prompt");
    socket.on("retval", function (data) {
        console.log(data);
    });
});

客户端:

<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect('http://ip:port');
    socket.on('prompt', function (data) {
        var username=prompt("Enter username");
        var password=prompt("Enter password");
        socket.emit("retval", { name: username, pass: password });
    });
</script>

当我打开页面时,我没有收到提示,只有当我终止节点进程(CTRL + C)时才会收到提示。

1 个答案:

答案 0 :(得分:0)

如果没有看到更多的代码,很难诊断出你的问题,但这是一个有效的例子:

var http = require("http");
var io;

var server = http.createServer(function(req, res) {
  res.writeHead(200, {"Content-Type": "text/html"});
  var html = "<script src='/socket.io/socket.io.js'></script>"
           + "<script>"
           + "  var socket = io.connect('http://localhost:8080');"
           + "  socket.on('prompt', function (data) {"
           + "    var username=prompt('Enter username');"
           + "    var password=prompt('Enter password');"
           + "    socket.emit('retval', { name: username, pass: password });"
           + "  });"
           + "</script>";
  res.end(html);
});

io = require("socket.io").listen(server);

io.sockets.on("connection", function (socket) {
  console.log("connection");
  socket.emit("prompt");
  socket.on("retval", function (data) {
    console.log(data);
  });
});

server.listen(8080);

console.log("Server listening on port 8080");

当您将其作为节点实例启动时,您应该在终端中看到此输出:

$ node server.js
  info - socket.io started
Server listening on port 8080

在浏览器中加载http://localhost:8080/,系统会显示用户名提示。