gpt4 book ai didi

javascript - 为什么我的 WebSocket 使用 Flask 自动关闭?

转载 作者:行者123 更新时间:2023-12-03 03:50:14 24 4
gpt4 key购买 nike

我使用 Flask 设置了一个非常基本的 Websocket 服务器。

websocket.py

from flask import Flask
from flask_uwsgi_websocket import GeventWebSocket
app = Flask(__name__)
ws = GeventWebSocket(app)
@app.route('/')
def index():
return render_template('index.html')
@ws.route('/foobar')
def echo(wscon):
msg = wscon.receive()
if msg is not None:
wscon.send(msg)
if __name__ == '__main__':
app.run(gevent=1000, host='0.0.0.0', port=9090)

index.html

<html>
<head>
<script language="Javascript">
var s = new WebSocket("ws://192.168.3.49:9090/foobar");
s.onopen = function() {
alert("connected !!!");
s.send("js send to server");
};
s.onmessage = function(e) {
alert("recv message")
var bb = document.getElementById('blackboard')
var html = bb.innerHTML;
bb.innerHTML = html + '<br/>' + e.data;
};

s.onerror = function(e) {
alert('error');
alert(e);
}

s.onclose = function(e) {
alert("connection closed");
}

function invia() {
var value = document.getElementById('testo').value;
alert(value);
s.send(value);
}
</script>
</head>
<body>
<h1>WebSocket</h1>
<input type="text" id="testo"/>
<input type="button" value="invia" onClick="invia();"/>
<div id="blackboard" style="width:640px;height:480px;background-color:black;color:white;border: solid 2px red;overflow:auto">
</div>
</body>

当我访问http://ip:9090时,我得到打击信息:

connected !!!

recv message

connection closed

为什么 websocket 自动关闭?而且偶尔会出现错误

[uwsgi-http key: 192.168.3.49:9090 client_addr: 192.168.3.1 client_port: 9177] hr_instance_read(): Connection reset by peer [plugins/http/http.c line 646]

最佳答案

似乎您正在尝试 echo gevent 服务器。 Example code

您需要保持连接循环运行。更改如下:

@ws.route('/foobar')
def echo(ws):
while True:
msg = ws.receive()
print(msg)
if msg is not None:
ws.send(msg)
else:
return

关于javascript - 为什么我的 WebSocket 使用 Flask 自动关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45203803/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com