websocket 群/单聊 基础
websocket 介绍
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1.用户A 给 用户B 发送一条消息 问 用户B 多久可以收到 用户A 的消息 电子邮件 - 可能是 一周期的时间 及时性很差 传达室大爷 - 消息托付 及时性很差 即时通讯 - 连接不断开的 2.轮询 长轮询 长连接 1.轮询 Http - 每秒钟发起至少100次,请求收取消息 - 客户端有一定的处理能力 - 服务器有极快的处理速度 缺点:客户端服务器,浪费资源严重,带宽浪费 2.长轮询 Http 先去连接服务器,不断开连接,保持一定时间,断开瞬间再次发起连接 - 浪费服务器资源严重 - 节省客户端资源 - 相对实时性消息 3.长连接 基于Http发起握手 保持和服务器的长连接永不断开 除非有一端主动发起断开请求 - 发是发 收是收 互不影响 - 在客户端 和 服务器上 各有一个轮询 - 双端分担压力 - 消息及时性 缺点:占用连接资源,占用网络资源
服务器主动给客户端发送消息 Web - Socket 客户端 与 服务器 达成一个协议 websocket 客户端 与 websocket 服务器 达成一个websocket协议
介绍引自 https://segmentfault.com/a/1190000012709475
群聊
from flask import Flask, request, render_template from geventwebsocket.handler import WebSocketHandler from gevent.pywsgi import WSGIServer from geventwebsocket.websocket import WebSocket #语法提示用 app = Flask(__name__) #实例化 user_socket_list = [] @app.route('/conn_ws') #http 协议, def ws_app(): user_socket = request.environ.get('wsgi.websocket') #type:WebSocket user_socket_list.append(user_socket) print(len(user_socket_list),user_socket_list) while True: # user_socket 是一个内存地址 msg = user_socket.receive() # hang 住了 print(msg) for usocket in user_socket_list: usocket.send(msg) # print(request.environ) # print(request.environ.get('wsgi.websocket'))# # --> <geventwebsocket.websocket.WebSocket object at 0x0379A9D0> ws对象 # return '555' # 遇到retur就断了 # 状态1 已经开启了 # 3 开启了,断开了 @app.route('/') def index(): return render_template('my_ws.html') if __name__ == '__main__': # app.run() http_serv = WSGIServer(('0.0.0.0',9009),app,handler_class=WebSocketHandler) # 应用程序网关接口 http_serv.serve_forever()
# 前端页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>群聊</title> </head> <body> <input type="text" id="send_str"> <button id="send_btn" onclick="send()">发消息</button> <div id="chat_list"> </div> </p> </body> <script type="text/javascript"> var ws = new WebSocket('ws://192.168.11.124:9009/conn_ws'); <!-- 创建连接 --> ws.onmessage = function (messageEvent) { console.log(messageEvent.data); var ptag = document.createElement('p'); ptag.innerText = messageEvent.data; document.getElementById('chat_list').appendChild(ptag); }; function send() { var send_str = document.getElementById('send_str').value; ws.send(send_str); } </script> </html>
单聊
from flask import Flask, request, render_template from geventwebsocket.handler import WebSocketHandler from gevent.pywsgi import WSGIServer from geventwebsocket.websocket import WebSocket import json app = Flask(__name__) user_socket_dict = {} # 字典 @app.route('/conn_ws/<user_nick>') #http 协议, def ws_app(user_nick): user_socket = request.environ.get('wsgi.websocket') #type:WebSocket user_socket_dict[user_nick] = user_socket # { 昵称:user信息 } print(len(user_socket_dict), list(user_socket_dict.keys()))
while True: # user_socket 是一个内存地址 msg = user_socket.receive() # hang 住了 msg_dict = json.loads(msg) to_user = msg_dict.get('to_user') to_user_socket = user_socket_dict.get(to_user) to_user_socket.send(msg) print(msg) # user_socket.send(msg) # print(request.environ.get('wsgi.websocket'))# # --> <geventwebsocket.websocket.WebSocket object at 0x0379A9D0> ws对象 # return '555' # 遇到retur就断了 # 状态1 已经开启了 # 3 开启了,断开了 @app.route('/') def index(): return render_template('my_ws.html') if __name__ == '__main__': # app.run() http_serv = WSGIServer(('0.0.0.0',9009),app,handler_class=WebSocketHandler) # 应用程序网关接口 http_serv.serve_forever()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>单聊</title> </head> <body> <p><input type="text" id="nick"> <button onclick="login()">登陆聊天室</button> </p> 发送给: <input type="text" id="to_user"> 消息: <input type="text" id="send_str"> <button id="send_btn" onclick="send()">发消息</button> <p> <div id="chat_list"> </div> </p> </body> <script type="text/javascript"> var ws = null; //公共变量, function login() { var nick = document.getElementById('nick').value; ws = new WebSocket('ws://192.168.11.124:9009/conn_ws/'+nick); //登录时候创建连接 ws.onmessage = function (messageEvent) { //等待消息 console.log(messageEvent.data); var ptag = document.createElement('p'); var message = JSON.parse( messageEvent.data); ptag.innerText =message.from_user + ' : '+ message.message ; document.getElementById('chat_list').appendChild(ptag); }; } function send() { var message = document.getElementById('send_str').value; var send_str = { from_user:document.getElementById('nick').value, to_user:document.getElementById('to_user').value, message:message }; var json_str = JSON.stringify(send_str); ws.send(json_str); } // js代码是异步代码; </script> </html>