websocket是什么?
web-socket是HTML5提出的一个协议规范,实现了浏览器和服务器之间的全双工通信web-socket约定了一个通信的规范,通过一个握手的机制,客户端(浏览器)和服务端(webserver)之间建立一个类似于tcp的连接,从而方便Client-Server,在websocket出现之前,web交互一般基于http协议的短连接和长连接
websocket的本质
websocket是为了解决客户端与服务端实时通信而产生的技术.websocket协议的本质上是个基于tcp协议,先通过Http/https协议发起一条特殊的http请求进行握手后创建一个用于交换数据的TCP连接,此后服务端与客户端通过此TCP连接进行实时通信,注意:此时不再需要原Http协议的参与了,这就意味着,它结合了tcp协议的稳定性和udp协议的实时性的优点,是非常NICE!!!
轮询,长轮询,长连接的特点(websocket之前)
轮询(Http)
特点:每秒发起至少100次,请求收取消息;客户端有一定的处理能力;服务器有极快的处理速度,能够实现通信的实时性
缺点:客户端和服务器,浪费资源严重,而且带宽浪费.
长轮询(Http)
特点:先去连接服务器,不断开连接,保持一定时间,断开瞬间再次发起连接;浪费服务器资源严重,却也因为能够保持一定时间连接,节省客户端资源;相对实时性消息
长连接(基于Http发起握手)
保持客户端和服务器的长连接永不断开,除非有一端主动发起断开请求;发是发,收是收,互不影响;在客户端和服务器上各有一个轮询,从而双端分担压力,消息能够实现及时性;但是占用连接资源,占用网络资源!
websocket的伟大之处
websocket API最伟大的地方在于服务器和客户端可以在给定的时间范围内的任意时刻,相互推送信息,浏览器和服务器只需要做一个握手的动作,在建立连接之后,服务器可以主动传送数据给客户端,客户端也可以随时向服务器发送数据,此外,服务器与客户端之间交换的标头信息很小
WebSocket应用
安装gevent-websocket模块..pip3 install gevent-websocket
from flask import Flask,render_template,request from geventwebsocket.handler import WebSocketHandler from geventwebsocket.websocket import WebSocket from gevent.pywsgi import WSGIServer app = Flask(__name__) user_socket_list = [] #建立一个user_socket空列表,存储不同的用户 @app.route('/conn_ws') def ws_app(): # print(request.environ)
''' 请求体信息 {'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_SOFTWARE': 'gevent/1.4 Python/3.6', 'SCRIPT_NAME': '', 'wsgi.version': (1, 0), 'wsgi.multithread': False, 'wsgi.multiprocess': False, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, 'SERVER_NAME': 'PC-201702021014', 'SERVER_PORT': '9527', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/conn_ws', 'QUERY_STRING': '', 'SERVER_PROTOCOL': 'HTTP/1.1', 'REMOTE_ADDR': '127.0.0.1', 'REMOTE_PORT': '54039', 'HTTP_HOST': '127.0.0.1:9527', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br', 'HTTP_ACCEPT_LANGUAGE': 'zh-CN,zh;q=0.9', 'HTTP_COOKIE': 'session=52cc7337-a096-4255-8ef6-557d44d5af8a', 'wsgi.input': <gevent.pywsgi.Input object at 0x0000000003A4AB28>, 'wsgi.input_terminated': True, 'werkzeug.request': <Request 'http://127.0.0.1:9527/conn_ws' [GET]>} {'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_SOFTWARE': 'gevent/1.4 Python/3.6', 'SCRIPT_NAME': '', 'wsgi.version': (1, 0), 'wsgi.multithread': False, 'wsgi.multiprocess': False, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, 'SERVER_NAME': 'PC-201702021014', 'SERVER_PORT': '9527', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/conn_ws', 'QUERY_STRING': '', 'SERVER_PROTOCOL': 'HTTP/1.1', 'REMOTE_ADDR': '127.0.0.1', 'REMOTE_PORT': '54513', 'HTTP_HOST': '127.0.0.1:9527', 'HTTP_CONNECTION': 'Upgrade', 'HTTP_PRAGMA': 'no-cache', 'HTTP_CACHE_CONTROL': 'no-cache', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36', 'HTTP_UPGRADE': 'websocket', 'HTTP_ORIGIN': 'http://localhost:63342', 'HTTP_SEC_WEBSOCKET_VERSION': '13', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br', 'HTTP_ACCEPT_LANGUAGE': 'zh-CN,zh;q=0.9', 'HTTP_COOKIE': 'session=52cc7337-a096-4255-8ef6-557d44d5af8a', 'HTTP_SEC_WEBSOCKET_KEY': 'ocNlT0TPOLSWLSSkbWT1OA==', 'HTTP_SEC_WEBSOCKET_EXTENSIONS': 'permessage-deflate; client_max_window_bits', 'wsgi.input': <gevent.pywsgi.Input object at 0x0000000003A4BB88>, 'wsgi.input_terminated': True, 'wsgi.websocket_version': '13', 'wsgi.websocket': <geventwebsocket.websocket.WebSocket object at 0x0000000003A40E80>, 'werkzeug.request': <Request 'http://127.0.0.1:9527/conn_ws' [GET]>} 'wsgi.websocket': <geventwebsocket.websocket.WebSocket object at 0x0000000003A40E80>, ''' # 拿到websocket对象, 可以建立连接 user_socket = request.environ.get('wsgi.websocket') # type:WebSocket user_socket_list.append(user_socket) #存放用户的情况信息和状态 print(len(user_socket_list),user_socket_list) while 1: #保持服务端一直处于启动状态 msg = user_socket.receive() print(msg) for usocket in user_socket_list: usocket.send(msg) """ WebSocket {url: "ws://127.0.0.1:9527/conn_ws", readyState: 1} ,如果readyState 为1 表示已经开启了websocket连接,且可以使用 如果readyState 为3 表示 开启了websocket,然后断开 """ if __name__ == '__main__': # app.run() http_server = WSGIServer(("127.0.0.1",9527),app,handler_class=WebSocketHandler) http_server.serve_forever()
群聊
1 #后端代码 2 from flask import Flask,render_template,request 3 from geventwebsocket.handler import WebSocketHandler 4 from geventwebsocket.websocket import WebSocket 5 from gevent.pywsgi import WSGIServer 6 7 app = Flask(__name__) 8 user_socket_list = [] 9 10 @app.route('/conn_ws') 11 def ws_app(): 12 user_socket = request.environ.get('wsgi.websocket') # type:WebSocket 13 user_socket_list.append(user_socket) 14 while 1: 15 msg = user_socket.receive() 16 print(msg) 17 for usocket in user_socket_list: 18 usocket.send(msg) 19 @app.route('/') 20 def index(): 21 return render_template('my_ws.html') 22 23 if __name__ == '__main__': 24 # app.run() 25 http_server = WSGIServer(("127.0.0.1",9527),app,handler_class=WebSocketHandler) 26 http_server.serve_forever()
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <input type="text" id="send_str"> 9 <button id="send_btn" onclick="send()">发送消息</button> 10 <p><div id="chat_list"></div></p> 11 </body> 12 13 <script type="application/javascript"> 14 var ws = new WebSocket('ws://127.0.0.1:9527/conn_ws'); 15 ws.onmessage = function (messageEvent) { 16 console.log(messageEvent.data); 17 var ptag = document.createElement('p'); 18 ptag.innerText = messageEvent.data; 19 document.getElementById('chat_list').appendChild(ptag); 20 }; 21 22 23 function send() { 24 var send_str = document.getElementById('send_str').value; 25 ws.send(send_str); 26 } 27 </script> 28 </html>
单聊
import json from flask import Flask,render_template,request from geventwebsocket.handler import WebSocketHandler from geventwebsocket.websocket import WebSocket from gevent.pywsgi import WSGIServer app = Flask(__name__) user_socket_dic ={} #单聊字典 ,从请求体中获取请求用户的信息做key,取对应的值 @app.route('/conn_ws/<user_nick>') def ws_app(user_nick=None): user_socket = request.environ.get('wsgi.websocket') # type:WebSocket user_socket_dic[user_nick] = user_socket print(len(user_socket_dic), list(user_socket_dic.keys()))# while 1: msg = user_socket.receive() #这个msg是bytes类型 msg_dic = json.loads(msg) #前端json序列化后拿到标准json字符串字典,json.loads取得正常字典 to_user = msg_dic.get('to_user') to_user_socket = user_socket_dic.get(to_user) #取到接收消息用户的链接 to_user_socket.send(msg) #把这个字典发出去 @app.route('/single_chat') def single_chat(): return render_template('single_chat.html') if __name__ == '__main__': # app.run() http_server = WSGIServer(("0.0.0.0",9527),app,handler_class=WebSocketHandler) http_server.serve_forever()
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <p><input type="text" id="nick"><button onclick="login()">登录聊天室</button></p> 9 发送给:<input type="text" id="to_user">消息:<input type="text" id="send_str"> 10 <button id="send_btn" onclick="send()">发送消息</button> 11 <p><div id="chat_list"></div></p> 12 </body> 13 14 <script type="application/javascript"> 15 var ws = null; 16 //ws.onopen = function(){ 17 // ws.send('123'); 18 //}; 19 function login() { 20 var nick = document.getElementById('nick').value; 21 ws = new WebSocket('ws://192.168.1.6:9527/conn_ws/'+nick); 22 ws.onmessage = function (messageEvent) { 23 console.log(messageEvent.data); 24 var ptag = document.createElement('p'); 25 var message = JSON.parse(messageEvent.data); 26 ptag.innerText = message.from_user + ":" + message.message; 27 document.getElementById('chat_list').appendChild(ptag); 28 }; 29 } 30 function send() { 31 var message = document.getElementById('send_str').value; 32 33 var send_str = { 34 from_user:document.getElementById('nick').value, 35 to_user:document.getElementById('to_user').value, 36 message:message 37 }; 38 var json_send_str = JSON.stringify(send_str); 39 ws.send(json_send_str); 40 } 41 </script> 42 </html>