简体   繁体   English

为什么我的Node.js服务器挂起了这个小脚本?

[英]Why does my Node.js server hang with this small script?

Edit: Answered below 编辑:下面回答

New to Node.js here, I really want to know why this script hangs forever when I'm attempting to connect to the created server. 这里是Node.js的新功能,我真的很想知道为什么当我尝试连接到创建的服务器时,此脚本永远挂起。

I've had this happen often enough when I'm trying to create a server and I'm not sure why, as it seems to happen with very similar code: 当我尝试创建服务器时,我经常发生这种情况,但我不确定为什么会发生这种情况,因为这似乎是通过非常相似的代码发生的:

Node script: 节点脚本:

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: 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>

If there is an error then it should end the response and if there isn't it should end the response, or does it have something to do with the web socket? 如果有错误,则应该结束响应,如果没有错误,则应该终止响应,或者它与Web套接字有关?

Try changing how you are invoking socket.io : 尝试更改您调用socket.io

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

websocket.on('connection', doStuff);

This example follows directly from the docs on GitHub . 此示例直接来自GitHub上的文档

The problem was with websocket.connect() . 问题出在websocket.connect() Socket.io uses io as a global object in the front end, not websocket . Socket.io使用io作为前端的全局对象,而不是websocket So it should have been io.connect() . 因此应该是io.connect()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM