简体   繁体   English

连接到socket.io服务器时,Web浏览器永远不会停止“加载”吗?

[英]Web browser never stops 'loading' when connecting to socket.io server?

I am having an issue with socket.io. 我在socket.io中遇到问题。 I have a nodejs server that's acting as a webserver while also running a socket.io server. 我有一个nodejs服务器,它同时充当网络服务器并同时运行socket.io服务器。 Additionally I have a webpage that connects to the socket.io server. 另外,我还有一个连接到socket.io服务器的网页。 The web page has one button that when clicked, emits a time update request. 网页上有一个按钮,单击该按钮会发出时间更新请求。 The socket.io server then sends back the time in milliseconds to the webpage which then updates a div to display the time. 然后,socket.io服务器将以毫秒为单位的时间发送回网页,然后该网页将更新div以显示时间。

This works fine, however, I've noticed that my web browser (Chrome) has the spinning loading icon in the tab and acts like the web page has never fully loaded. 效果很好,但是,我注意到我的网络浏览器(Chrome)在选项卡中有旋转的加载图标,其行为就像网页从未完全加载一样。 It also displays the 'X' to stop loading a page. 它还显示“ X”以停止加载页面。

If I click the 'X' to stop loading the page, my software continues to work fine, but I cannot figure out why the page never completely loads. 如果单击“ X”停止加载页面,我的软件将继续正常运行,但是我无法弄清为什么页面从未完全加载。

Server Code: 服务器代码:

var http = require("http");
var wrHandler = require("./webRequestHandler");
var io = require("socket.io");
var parser = require("./messageParser");

function start() {
    function onRequest(request, response){
        wrHandler.handle(request, response);        
    }

    var webserver = http.createServer(onRequest).listen(8888);
    console.log("Server has started.");



    var ioserver = io.listen(webserver);
    ioserver.set('log level', 3);
    ioserver.sockets.on('connection', function(socket){
        parser.parse(socket);
    });

}

exports.start = start;

Web Request Handler: Web请求处理程序:

var url = require("url");
var fs = require("fs");

function handle(request, response){
    var pathname = url.parse(request.url).pathname;
    console.log(pathname);

        switch(pathname){
            case '/':
                fs.readFile("../html/index.html", function(error, data){
                    if(error){
                        response.writeHead(404);
                        response.write("This file does not exist.");
                    }
                    else{
                        response.writeHead(200, {"Content-Type": "text/html"});
                        response.write(data, "utf8");
                    }
                });
                break;
            default:
                fs.readFile("../html" + pathname, function(error, data){
                    if(error){
                        response.writeHead(404, {"Content-Type": "text/html"});
                        response.write("<html><body>This file does not exist!</body></html>");
                        console.log("Test");
                    }
                    else{
                        response.writeHead(200, {"Content-Type": "text/html"});
                        response.write(data, "utf8");
                    }
                });
        }
}

exports.handle = handle;

Message Parser: 消息解析器:

function parseMessage(socket){
    socket.on('client_msg',function(data){
        var msgID = data.msgID;

        switch(msgID){
            case "gettime": 
                socket.emit('timeupdate', {"time": new Date().getTime()});
                break;
            default: break;
        }
    });
}

exports.parse = parseMessage;

HTML Page: HTML页面:

<html>
    <head>
        <script src="/socket.io/socket.io.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
        <script>
            var socket = io.connect();

            function getTime(){
                socket.emit('client_msg', {"msgID": "gettime"});
            }

            socket.on('timeupdate', function(data){
                $("#time").text(data.time);
            });
        </script>
    </head>
    <body>

        <input type="button" value="Get Server Time" onclick="getTime()"/>
        <div id="time">

        </div>
    </body>
</html>

I should admit that I'm very new to node.js and not the strongest javascript developer either. 我应该承认,我对node.js并不陌生,也不是最强大的javascript开发人员。 Any criticism/advice/hints are greatly appreciated. 任何批评/建议/提示都将不胜感激。

In your web request handler, at the end, do response.end() right outside of your switch block. 最后,在Web请求处理程序中, 在switch块外部执行response.end()。

Edit: You have to do it at the end of each write, because you are doing asynchronous file reading. 编辑:您必须在每次写入结束时执行此操作,因为您正在执行异步文件读取。 If you use readFileSync, you could write it once at the end. 如果使用readFileSync,则可以在末尾写入一次。

http://nodejs.org/api/http.html#http_response_end_data_encoding http://nodejs.org/api/http.html#http_response_end_data_encoding

So your file would look like like: 因此,您的文件如下所示:

    var url = require("url");
    var fs = require("fs");

    function handle(request, response){
        var pathname = url.parse(request.url).pathname;
        console.log(pathname);

            switch(pathname){
                case '/':
                    fs.readFile("../html/index.html", function(error, data){
                        if(error){
                            response.writeHead(404);
                            response.write("This file does not exist.");
                            response.end();
                        }
                        else{
                            response.writeHead(200, {"Content-Type": "text/html"});
                            response.write(data, "utf8");
                            response.end();
                        }
                    });
                    break;
                default:
                    fs.readFile("../html" + pathname, function(error, data){
                        if(error){
                            response.writeHead(404, {"Content-Type": "text/html"});
                            response.write("<html><body>This file does not exist!</body></html>");
                            response.end();
                            console.log("Test");
                        }
                        else{
                            response.writeHead(200, {"Content-Type": "text/html"});
                            response.write(data, "utf8");
                            response.end();
                        }
                    });
            }
    }

    exports.handle = handle;

Note that response.end('foo'); 注意response.end('foo'); is equivalent to response.write('foo'); 等价于response.write('foo'); response.end(); 到Response.End();

Also, I know this is a bit off topic, but you should try out the express framework for node. 另外,我知道这是一个有点题外话,但您应该尝试使用node的快速框架。 It makes a lot of web request handling easy without being overly opinionated. 它使许多Web请求处理变得容易,而又不会引起过多的怀疑。

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

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