Flask websocker
2021-05-11 18:27
阅读:378
YPE >
标签:eth name cal user while 偏函数 create family pip
群聊版
安装
pip?install?gevent-websocket??
?
视图
- #?-*-?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()??
?
前端
- html>??
- ?lang="en">??
- ??
- ???? ?charset="UTF-8">??
- ????
ws?? - ??
- ??
- ?type="text"?id="msg">?发送??
- ?? ?
- ?id="chat_list"?style="width:?500px;?height:?500px;">???? ?
?? - ?? ?
- ??
- ?? ?
- ??
- ????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)??
- ????}??
- ??
- ??
?
一对一单机版
视图
- #?-*-?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/
‘)?? - 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()??
?
前端
- html>??
- ?lang="en">??
- ??
- ???? ?charset="UTF-8">??
- ????
ws?? - ??
- ??
- ?type="text"?id="username">?登陆聊天室??
- ?? ?
- 给?type="text"?id="to_user">发送:?type="text"?id="msg">?发送??
- ?? ?
- ?id="chat_list"?style="width:?500px;?height:?500px;">???? ?
?? - ?? ?
- ??
- ?? ?
- ??
- ????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));??
- ????}??
- ??
- ??
?
Websocker
视图
- 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"]‘?
?‘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‘)??
前端
- html>??
- ?lang="en">??
- ??
- ???? ?charset="UTF-8">??
- ???? ?http-equiv="x-ua-compatible"?content="IE=edge">??
- ???? ?name="viewport"?content="width=device-width,?initial-scale=1">??
- ????
test?? - ??
- ??
- ??
- ?? ?
- ??
- ?type="text"?id="message"?value="Hello,?World!"/>??
- 发送?message??
- ?? ?
- ??
- ??
- ??
- ????//?判断浏览器是否支持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?=?"
"?+?msg.data?+?"
";?? - ????????????$("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();??
- ?? ?
- ????});??
- ?? ?
- ??
- ??
Flask websocker
标签:eth name cal user while 偏函数 create family pip
原文地址:https://www.cnblogs.com/py-web/p/12016495.html
上一篇:JSON格式学习练习
下一篇:web3 编译部署调用合约
评论
亲,登录后才可以留言!