我已经使用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时,我收到了打击信息:
连接!!!
recv message
连接关闭
为什么websocket自动关闭?偶尔也会出现错误
[uwsgi-http key:192.168.3.49:9090 client_addr:192.168.3.1 client_port:9177] hr_instance_read():由对等方重置连接 [plugins / http / http.c第646行]
答案 0 :(得分:1)
好像你正在尝试使用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