Flask websocker
程序员文章站
2022-06-23 22:52:25
群聊版 安装 pipinstallgevent-websocket 视图 #-*-coding:utf-8-*- importjson fromflaskimportFlask,request,render_template fromgeventwebsocket.handlerimportWebS... ......
群聊版
安装
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()
前端
- <!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>
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"]' <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>