【问题标题】:Why does my Node.js server hang with this small script?为什么我的 Node.js 服务器挂起这个小脚本?
【发布时间】:2016-04-12 22:16:39
【问题描述】:

编辑:在下面回答

这里是 Node.js 的新手,我真的很想知道为什么当我尝试连接到创建的服务器时这个脚本永远挂起。

我在尝试创建服务器时经常发生这种情况,但我不知道为什么,因为它似乎发生在非常相似的代码中:

节点脚本:

var http = require("http");
var file = require("fs");

var server = http.createServer(function(request, response)
{
    file.readFile("chat.html", "UTF-8", function(error, content)
    {
        if(error) { console.error(error.stack); response.end(); }
        response.writeHead(200, {"content-type" : "text/html"});
        response.end(content);
    });
}).listen(1994, function(){console.log("Listening");});

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

websocket.sockets.on("connection", function(socket)
{
    socket.emit("message", {"message" : "Hello World"});
});

HTML:

<!DOCTYPE HTML>
<html>
    <head>
        <title>Chat</title>
        <meta charset="utf-8">
        <script src="/socket.io/socket.io.js"></script>
        <script>
            var socket = websocket.connect();

            socket.on("message", function(message)
            {
                console.log(message);
            });
        </script>
    </head>
    <body>
        <div>Socket file.</div>
    </body>
</html>

如果有错误则应该结束响应,如果没有则应该结束响应,还是与网络套接字有关?

【问题讨论】:

  • .readFile() 出现错误时,您并没有退出回调函数,尽管我不确定这将如何挂起服务器。
  • 我编辑了我的代码以反映我当前的代码。无论我自己只有response.end() 还是response.end(); return false;,都不能解决挂起的问题。我怀疑这是网络套接字的问题。
  • 我仍然认为你应该在出现错误时return,但这可能不是问题所在。

标签: javascript node.js websocket socket.io


【解决方案1】:

尝试改变调用socket.io的方式:

var websocket = require('socket.io')(server);

websocket.on('connection', doStuff);

这个例子直接来自the docs on GitHub

【讨论】:

    【解决方案2】:

    问题在于websocket.connect()。 Socket.io 在前端使用io 作为全局对象,而不是websocket。所以应该是io.connect()

    【讨论】:

      猜你喜欢
      • 2011-02-09
      • 2016-01-31
      • 2016-02-15
      • 2010-09-16
      • 2011-06-25
      • 1970-01-01
      • 2015-07-11
      • 2017-02-13
      • 2020-12-14
      相关资源
      最近更新 更多