#?-*-?coding:?utf-8?-*-??
import?json??
from?flask?import?Flask,?request,?render_template??
from?geventwebsocket.handler?import?WebSocketHandler??#?导入websocker的方法??
from?gevent.pywsgi?import?WSGIServer??
??
?
app?=?Flask(__name__)??
??
?
user_socker_list?=?[]??#?保存所有的websocker对象??
??
?
@app.route(‘/ws‘)??
def?ws():??
????#?print(request.headers)??
????user_socker?=?request.environ.get(‘wsgi.websocket‘)??#?type??WebSocket??
??
?
????"""??
????readyState:?3??连接正常,然后断开??
????readyState:?1??表示正常连接??
????"""??
????if?user_socker:??
????????user_socker_list.append(user_socker)??
????????while?1:??
????????????msg?=?user_socker.receive()??#?接收消息??
????????????print(msg)??#?接受完信息后断开,所有加循环变成长连接??
????????????for?u_socker?in?user_socker_list:??
????????????????if?u_socker?==?user_socker:??
????????????????????continue??
????????????????try:??
????????????????????u_socker.send(msg)??
????????????????except:??
????????????????????continue??
??
?
????return?render_template(‘ws.html‘)??
??
?
??
?
if?__name__?==?‘__main__‘:??
????#?app.run(host=‘0.0.0.‘,?debug=True)??
????http_serv?=?WSGIServer((‘0.0.0.0‘,?5000),?app,?handler_class=WebSocketHandler)??
????http_serv.serve_forever()??
<!DOCTYPE?html>??
<html?lang="en">??
<head>??
????<meta?charset="UTF-8">??
????<title>ws</title>??
</head>??
<body>??
<input?type="text"?id="msg">?<button?onclick="snd_msm()">发送</button>??
??
?
<div?id="chat_list"?style="width:?500px;?height:?500px;">??
??
?
</div>??
??
?
</body>??
??
?
<script?type="application/javascript">??
????var?ws?=?new?WebSocket(‘ws://192.168.32.71:5000/ws‘);??{#?设置websocker连接?#}??
????ws.onmessage?=?function?(data)?{??
????????console.log(data.data);??{#?数据在data。data里面?#}??
????????var?ptag?=?document.createElement(‘p‘);??
????????ptag.innerText?=?data.data;??
????????document.getElementById(‘chat_list‘).appendChild(ptag)??
??
?
????};?{#?打印收到的数据?#}??
??????
?
????function?snd_msm()?{??
????????var?msg?=?document.getElementById(‘msg‘).value;??
????????ws.send(msg)??
????}??
</script>??
</html>??
#?-*-?coding:?utf-8?-*-??
import?json??
from?flask?import?Flask,?request,?render_template??
from?geventwebsocket.handler?import?WebSocketHandler??#?导入websocker的方法??
from?gevent.pywsgi?import?WSGIServer??
??
?
app?=?Flask(__name__)??
??
?
user_socker_dict?=?{}??#?这里仿照flask上下文的方式??
??
?
"""??
借用??
flask?上下文??
??
?
{??
"线程id":?偏函数,??
"线程id":?偏函数,??
}??
"""??
??
?
@app.route(‘/ws2/<usename>‘)??
def?ws2(usename):??
????#?print(request.headers)??
????user_socker?=?request.environ.get(‘wsgi.websocket‘)??#?type??WebSocket??
??
?
????"""??
????readyState:?3??连接正常,然后断开??
????readyState:?1??表示正常连接??
????"""??
????print(user_socker)??
????if?user_socker:??
????????user_socker_dict[usename]?=?user_socker??
????????print(user_socker_dict)??
????????while?1:??
????????????msg?=?user_socker.receive()??#?接收人,消息,发送人??
????????????msg_dict?=?json.loads(msg)??
????????????msg_dict[‘from_user‘]?=?usename??
????????????to_user?=?msg_dict.get(‘to_user‘)??
????????????u_socker?=?user_socker_dict.get(to_user)??#?type??WebSocket??
????????????u_socker.send(json.dumps(msg_dict))??
??
?
????return?render_template(‘ws2.html‘)??
??
?
??
?
if?__name__?==?‘__main__‘:??
????#?app.run(host=‘0.0.0.‘,?debug=True)??
????http_serv?=?WSGIServer((‘0.0.0.0‘,?5000),?app,?handler_class=WebSocketHandler)??
????http_serv.serve_forever()??
<!DOCTYPE?html>??
<html?lang="en">??
<head>??
????<meta?charset="UTF-8">??
????<title>ws</title>??
</head>??
<body>??
<input?type="text"?id="username">?<button?onclick="login()">登陆聊天室</button>??
??
?
给<input?type="text"?id="to_user">发送:<input?type="text"?id="msg">?<button?onclick="snd_msm()">发送</button>??
??
?
<div?id="chat_list"?style="width:?500px;?height:?500px;">??
??
?
</div>??
??
?
</body>??
??
?
<script?type="application/javascript">??
????var?ws?=?null;??{#?为什么设置null,?被其他函数执行?#}??
??
?
????function?login()?{??
????????var?username?=?document.getElementById(‘username‘).value;??
????????ws?=?new?WebSocket(‘ws://192.168.32.71:5000/ws2/‘?+?username);??{#?设置websocker连接?#}??
????????ws.onmessage?=?function?(data)?{??
????????????var?recv_msg?=?JSON.parse(data.data);??
????????????var?ptag?=?document.createElement(‘p‘);??
????????????ptag.innerText?=?recv_msg.from_user?+?":"?+?recv_msg.msg;??
????????????document.getElementById(‘chat_list‘).appendChild(ptag)??
????????};?{#?打印收到的数据?#}??
??
?
????}??
??
?
????function?snd_msm()?{??
????????var?to_user?=?document.getElementById(‘to_user‘).value;??
????????var?msg?=?document.getElementById(‘msg‘).value;??
????????send_msg?=?{??
????????????"to_user"?:?to_user,??
????????????"msg":?msg??
????????};??
????????ws.send(JSON.stringify(send_msg));??
????}??
</script>??
</html>??
import?time??
from?django.shortcuts?import?render??
from?dwebsocket.decorators?import?accept_websocket??
??
?
??
?
@accept_websocket??
def?test(request):??
????if?request.is_websocket():??
????????print(‘websocket?connection....‘)??
????????msg?=?request.websocket.wait()??#?接收前端发来的消息??
????????print(msg,?type(msg),?json.loads(msg))??#?b‘["1","2","3"]‘?<class?‘bytes‘>?[‘1‘,?‘2‘,?‘3‘]??
????????while?1:??
????????????if?msg:??
????????????????#?你要返回的结果??
????????????????for?i?in?range(10):??
????????????????????request.websocket.send(str(i).encode())??#?向客户端发送数据??
????????????????request.websocket.close()??
????else:??#?如果是普通的请求返回页面??
????????return?render(request,?‘test.html‘)??
<!DOCTYPE?html>??
<html?lang="en">??
<head>??
????<meta?charset="UTF-8">??
????<meta?http-equiv="x-ua-compatible"?content="IE=edge">??
????<meta?name="viewport"?content="width=device-width,?initial-scale=1">??
????<title>test</title>??
</head>??
<body>??
<div></div>??
??
?
</body>??
<input?type="text"?id="message"?value="Hello,?World!"/>??
<button?type="button"?id="send_message">发送?message</button>??
??
?
<!--?首先引入?jQuery?-->??
<script?src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>??
<script>??
????//?判断浏览器是否支持WebSocket,目前应该所有的浏览器都支持了.....??
????if?(‘WebSocket‘?in?window)?{??
????????console.log(‘你的浏览器支持?WebSocket‘)??
????}??
????$(‘#send_message‘).click(function?()?{??
????????//?创建一个WebSocket对象:sk,并且建立与服务端的连接(服务端程序要跑着哦)??
????????var?sk?=?new?WebSocket(‘ws://‘?+?window.location.host?+?‘/asset/test/‘);??
????????//?向服务端发送消息??
????????sk.onopen?=?function?()?{??
????????????console.log(‘websocket?connection?successful...‘);??
????????????var?datas?=?$(‘#message‘).val();??
????????????sk.send(JSON.stringify(datas));??
????????};??
????????//?接收服务端的消息,主要的业务逻辑也在这里完成??
????????sk.onmessage?=?function?(msg)?{??
????????????//?业务逻辑??
????????????html?=?"<p>"?+?msg.data?+?"</p>";??
????????????$("div").append(html);??
????????????console.log(‘from?service?message:?‘,?msg.data);??
????????????//?由于服务端主动断开连接,这里也断开WebSocket连接??
????????????if?(sk.readyState?==?WebSocket.CLOSED)?sk.close();??
????????};??
????????//?完事就关闭WebSocket连接??
????????sk.onclose?=?function?(msg)?{??
????????????console.log(‘websocket?connection?close...‘);??
????????????sk.close()??
????????};??
????????//?当WebSocket连接创建成功后,我们就可以向服务端发送数据了??
????????if?(sk.readyState?==?WebSocket.OPEN)?sk.onopen();??
??
?
????});??
??
?
</script>??
</html>??