简易后端
# 不需要记住 但是要知道是什么模块驱使Flask 支持Websocket
# gevent-websocket
# 以下代码 和 gevent-websocket 使用方式 请记录在案
from geventwebsocket.handler import WebSocketHandler
from geventwebsocket.server import WSGIServer
from geventwebsocket.websocket import WebSocket # 语法提示
from flask import Flask, request, render_template
app = Flask(__name__)
socket_list = []
@app.route("/ws")
def ws():
sock = request.environ.get("wsgi.websocket") # type:WebSocket
socket_list.append(sock)
print(socket_list)
# 1 : 连接打开
# 2 : 客户端主动关闭连接
# 3 : 连接关闭 由服务器发起
# 0 : 连接中。。。。。。
while 1:
try:
msg = sock.receive() # hello
except:
socket_list.remove(sock)
break
for so in socket_list:
if so == sock:
continue
try:
so.send(msg)
except:
continue
return "200OK"
# return "200 OK"
@app.route("/")
def index():
return render_template("ws_client.html")
if __name__ == '__main__':
# app.run()
http_serv = WSGIServer(("0.0.0.0", 9527), app, handler_class=WebSocketHandler) # environment
http_serv.serve_forever()
简易前端
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
</head>
<body>
<h1>你好,世界!</h1>
<input type="text" id="text"> <button id="send">点击发送消息</button>
<div id="content_list">
</div>
</body>
<script type="application/javascript">
var ws = new WebSocket("ws://192.168.14.26:9527/ws");
// 回调函数
// onopen websocket连接建立完成 status == 1
// ws.onopen = function () {
// ws.send("Hello");
// };
// onmessage websocket 接收到消息时 执行
ws.onmessage = function (eventMessage) {
var s = eventMessage.data;
var p = document.createElement("p");
p.innerText = s;
document.getElementById("content_list").appendChild(p);
};
// ws.onclose
// ws.send("123");
document.getElementById("send").addEventListener("onclick",function () {
var st = document.getElementById("text").value();
ws.send(st);
})
</script>
</html>