WebSocket 已经处于 CLOSING 或 CLOSED 状态 - HTML

Dan*_*sta 5 html python websocket

我是 HTML5/javascript 的新手,我使用 python 创建了一个 websocket 服务器。
我想查看数据并在文本区域中添加收到的消息,不确定出了什么问题,但它在第一次尝试发送消息时工作正常,但WebSocket is already in CLOSING or CLOSED state在发送另一个消息时抛出“ ”。

我在 html 中遗漏了什么吗?

<!DOCTYPE HTML>

<html>
   <head>
      <script type="text/javascript">
		var connection = new WebSocket("ws://localhost:8765");
		
		connection.onopen = function () {
			console.log('Connection Opened');
		};

		connection.onerror = function (error) {
			console.log('WebSocket Error ' + error);
		};

		connection.onmessage = function (e) {
			document.getElementById("rxConsole").value += e.data;
		};
	
		function sendMessage(msg){
			console.log('I\'m sending data');
			connection.send(document.getElementById("txBar").value);
			document.getElementById("txBar").value = "";
		}
</script>

	  
		
   </head>
   <body">
   <div>
		 <textarea id="rxConsole"></textarea
	</div>
	<hr/>
	<div>
		<input type ="text" id="txBar" onkeydown="if(event.keyCode == 13) sendMessage();" />
   </body>
</html>
Run Code Online (Sandbox Code Playgroud)

蟒蛇代码:

import asyncio
import websockets

async def hello(websocket, path):
    name = await websocket.recv()
    print(f"< {name}")

    greeting = f"Hello {name}!"

    await websocket.send(greeting)
    print(f"> {greeting}")

start_server = websockets.serve(hello, 'localhost', 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Run Code Online (Sandbox Code Playgroud)

从铬:

在此处输入图片说明