之后再更新几篇完善的功能
web_socket/templates/index.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>ws测试</title>
</head>
<body>
<main>
<div class="left">
<input type="text" id="text">
<button id="button-send">发送</button>
</div>
<div class="right">
<div id="content"></div>
</div>
</main>
<script>
function show_message(text){
document.getElementById('content').innerText+='服务器发来的消息: '+ text +'\n';
}
/*
if (!('WebSocket' in window)){
alert('您的浏览器不支持 WebSocket!');
}
*/
var ws = new WebSocket('ws://www.wangsuyin.top:5001/echo');
ws.onopen = function(){
console.log('web socket 已连接');
}
ws.onmessage = function (event){
r_data = event.data; //接收到的数据
console.log(r_data);
show_message(r_data);
}
ws.onclose = function(){
//alert('连接已关闭...');
}
document.getElementById('button-send').onclick = function(event){
var text = document.getElementById('text').value ;
ws.send( text);
document.getElementById('content').innerText += '我: ' + text +'\n';
}
</script>
</body>
</html>
web_socket/server.py
#https://www.jianshu.com/p/ad79148f4c11
#https://www.runoob.com/html/html5-websocket.html
from flask import Flask,render_template,request
from flask_sockets import Sockets
app = Flask(__name__)
sockets = Sockets(app)
ws_pool = []
# ws://localhost:5001/echo
@sockets.route('/echo')
def echo_socket(ws):
for e in ws_pool:
e.send('有人进来了!')
ws_pool.append(ws)
while not ws.closed:
r_data = ws.receive()
if r_data is None:
break
# ws.send("客户端已收到: " + str(message))
#如何推送给其他人
for e in ws_pool:
if e ==ws:
continue
e.send('有人说:{}'.format(r_data))
ws_pool.remove(ws)
for e in ws_pool:
e.send('有人黯然离去!')
@app.route('/')
def index():
return render_template('index.html')
if __name__ == "__main__":
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
server = pywsgi.WSGIServer(('0.0.0.0', 5001), app, handler_class=WebSocketHandler)
print("web server start ... ")
server.serve_forever()
网友评论