0

我有这个代码:

服务器(使用 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)时才收到提示。

4

1 回答 1

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/在浏览器中加载,应该会出现用户名提示。

于 2013-09-03T14:27:41.807 回答