群聊版
安装
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/<usename>')
- def ws(usename):
- # 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_dict:
- if u_socker == user_socker:
- continue
- try:
- u_socker.send(msg)
- except:
- continue
- return render_template('ws.html')
前端
- <!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>