javascript 为什么我的 WebSocket 会自动关闭?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19945792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:19:10  来源:igfitidea点击:

Why is my WebSocket automatically closing?

javascriptpythonwebsockettornado

提问by mavix

I've set up a very basic websocket server using tornado:

我已经使用 Tornado 设置了一个非常基本的 websocket 服务器:

import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.httpserver

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print 'new connection'
        self.write_message("Hello World")

    def on_message(self, message):
        print 'message received %s' % message

    def on_close(self):
      print 'connection closed'


application = tornado.web.Application([
  (r'/ws', WSHandler),
])


if __name__ == "__main__":
  http_server = tornado.httpserver.HTTPServer(application)
  http_server.listen(8000)
  tornado.ioloop.IOLoop.instance().start()

and a very basic client, that should be able to continually ping the server via a button click:

和一个非常基本的客户端,它应该能够通过单击按钮不断地 ping 服务器:

<!DOCTYPE html>  
<meta charset="utf-8" />  
<title>WebSocket Test</title>  
<script language="javascript" type="text/javascript">

    var wsUri = "ws://localhost:8000/ws";
    var websocket = new WebSocket(wsUri);
    var output;
    function init() { 
        output = document.getElementById("outputDiv");
        if (!'WebSocket' in window){
            writeToScreen('<span style="color: red;">ERROR: Update your browser to one that supports websockets. A list can be found <a href="http://caniuse.com/websockets">here</a></span>');
        } else {
            testWebSocket();
        }
    }
    function onOpen(evt) { 
        writeToScreen("CONNECTED");
        doSend("Hi there!");
    }
    function onClose(evt) { 
        writeToScreen("DISCONNECTED");
    }
    function onMessage(evt) { 
        writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
        websocket.close();
    }
    function onError(evt) { 
        writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
    }
    function doSend(message) { 
        writeToScreen("SENT: " + message);
        websocket.send(message);
    }
    function writeToScreen(message) { 
        var pre = document.createElement("p");
        pre.style.wordWrap = "break-word";
        pre.innerHTML = message;
        output.appendChild(pre);
    }
    function testWebSocket() {
        websocket.onopen = function(evt) { onOpen(evt) };
        websocket.onclose = function(evt) { onClose(evt) };
        websocket.onmessage = function(evt) { onMessage(evt) };
        websocket.onerror = function(evt) { onError(evt) };
        document.getElementById("send").onclick = function () {
            doSend(document.getElementById("inputTxt").value);
            console.log("click registered.");
        };

    }
    window.addEventListener("load", init, false);
</script>  
</div>
<h2>WebSocket Test</h2> 
<div id="inputDiv">
    <input id="inputTxt" type="text"/>
    <button id="send" onclick=>send</button>
</div>
<div id="outputDiv">
</div>
</html>

When I load the page, I get:

当我加载页面时,我得到:

CONNECTED
SENT: Hi there!
RESPONSE: Hello World
DISCONNECTED

已连接
:您好!
响应:Hello World 已
断开连接

If I click the button, I get an error:

如果我单击该按钮,则会收到错误消息:

WebSocket is already in CLOSING or CLOSED state.

WebSocket 已经处于 CLOSING 或 CLOSED 状态。

But, if I re-instantiate the websocket object in the command line (via chrome developer tools), the button works, and the connection is not closed. I feel that this must be some idiosyncrasy of javascript that I don't understand, because if the object is still in scope, I don't understand why it would have automatically closed the connection.

但是,如果我在命令行中重新实例化 websocket 对象(通过 chrome 开发人员工具),按钮会起作用,并且连接不会关闭。我觉得这一定是我不明白的 javascript 特性,因为如果对象仍在范围内,我不明白为什么它会自动关闭连接。

采纳答案by mavix

Derp. The onMessage function is closing it:

德普。onMessage 函数正在关闭它:

function onMessage(evt) { 
    writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
    websocket.close();
}