WebSocket

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>
群聊~前端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>
单聊HTML代码

 

posted @ 2019-03-24 22:11  FindSoul  阅读(215)  评论(0编辑  收藏  举报
var RENDERER = { POINT_INTERVAL : 5, FISH_COUNT : 3, MAX_INTERVAL_COUNT : 50, INIT_HEIGHT_RATE : 0.5, THRESHOLD : 50, init : function(){ this.setParameters(); this.reconstructMethods(); this.setup(); this.bindEvent(); this.render(); }, setParameters : function(){ this.$window = $(window); this.$container = $('#jsi-flying-fish-container'); this.$canvas = $('
'); this.context = this.$canvas.appendTo(this.$container).get(0).getContext('2d-disabled'); this.points = []; this.fishes = []; this.watchIds = []; }, createSurfacePoints : function(){ var count = Math.round(this.width / this.POINT_INTERVAL); this.pointInterval = this.width / (count - 1); this.points.push(new SURFACE_POINT(this, 0)); for(var i = 1; i < count; i++){ var point = new SURFACE_POINT(this, i * this.pointInterval), previous = this.points[i - 1]; point.setPreviousPoint(previous); previous.setNextPoint(point); this.points.push(point); } }, reconstructMethods : function(){ this.watchWindowSize = this.watchWindowSize.bind(this); this.jdugeToStopResize = this.jdugeToStopResize.bind(this); this.startEpicenter = this.startEpicenter.bind(this); this.moveEpicenter = this.moveEpicenter.bind(this); this.reverseVertical = this.reverseVertical.bind(this); this.render = this.render.bind(this); }, setup : function(){ this.points.length = 0; this.fishes.length = 0; this.watchIds.length = 0; this.intervalCount = this.MAX_INTERVAL_COUNT; this.width = this.$container.width(); this.height = this.$container.height(); this.fishCount = this.FISH_COUNT * this.width / 500 * this.height / 500; this.$canvas.attr({width : this.width, height : this.height}); this.reverse = false; this.fishes.push(new FISH(this)); this.createSurfacePoints(); }, watchWindowSize : function(){ this.clearTimer(); this.tmpWidth = this.$window.width(); this.tmpHeight = this.$window.height(); this.watchIds.push(setTimeout(this.jdugeToStopResize, this.WATCH_INTERVAL)); }, clearTimer : function(){ while(this.watchIds.length > 0){ clearTimeout(this.watchIds.pop()); } }, jdugeToStopResize : function(){ var width = this.$window.width(), height = this.$window.height(), stopped = (width == this.tmpWidth && height == this.tmpHeight); this.tmpWidth = width; this.tmpHeight = height; if(stopped){ this.setup(); } }, bindEvent : function(){ this.$window.on('resize', this.watchWindowSize); this.$container.on('mouseenter', this.startEpicenter); this.$container.on('mousemove', this.moveEpicenter); this.$container.on('click', this.reverseVertical); }, getAxis : function(event){ var offset = this.$container.offset(); return { x : event.clientX - offset.left + this.$window.scrollLeft(), y : event.clientY - offset.top + this.$window.scrollTop() }; }, startEpicenter : function(event){ this.axis = this.getAxis(event); }, moveEpicenter : function(event){ var axis = this.getAxis(event); if(!this.axis){ this.axis = axis; } this.generateEpicenter(axis.x, axis.y, axis.y - this.axis.y); this.axis = axis; }, generateEpicenter : function(x, y, velocity){ if(y < this.height / 2 - this.THRESHOLD || y > this.height / 2 + this.THRESHOLD){ return; } var index = Math.round(x / this.pointInterval); if(index < 0 || index >= this.points.length){ return; } this.points[index].interfere(y, velocity); }, reverseVertical : function(){ this.reverse = !this.reverse; for(var i = 0, count = this.fishes.length; i < count; i++){ this.fishes[i].reverseVertical(); } }, controlStatus : function(){ for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].updateSelf(); } for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].updateNeighbors(); } if(this.fishes.length < this.fishCount){ if(--this.intervalCount == 0){ this.intervalCount = this.MAX_INTERVAL_COUNT; this.fishes.push(new FISH(this)); } } }, render : function(){ requestAnimationFrame(this.render); this.controlStatus(); this.context.clearRect(0, 0, this.width, this.height); this.context.fillStyle = 'hsl(0, 0%, 95%)'; for(var i = 0, count = this.fishes.length; i < count; i++){ this.fishes[i].render(this.context); } this.context.save(); this.context.globalCompositeOperation = 'xor'; this.context.beginPath(); this.context.moveTo(0, this.reverse ? 0 : this.height); for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].render(this.context); } this.context.lineTo(this.width, this.reverse ? 0 : this.height); this.context.closePath(); this.context.fill(); this.context.restore(); } }; var SURFACE_POINT = function(renderer, x){ this.renderer = renderer; this.x = x; this.init(); }; SURFACE_POINT.prototype = { SPRING_CONSTANT : 0.03, SPRING_FRICTION : 0.9, WAVE_SPREAD : 0.3, ACCELARATION_RATE : 0.01, init : function(){ this.initHeight = this.renderer.height * this.renderer.INIT_HEIGHT_RATE; this.height = this.initHeight; this.fy = 0; this.force = {previous : 0, next : 0}; }, setPreviousPoint : function(previous){ this.previous = previous; }, setNextPoint : function(next){ this.next = next; }, interfere : function(y, velocity){ this.fy = this.renderer.height * this.ACCELARATION_RATE * ((this.renderer.height - this.height - y) >= 0 ? -1 : 1) * Math.abs(velocity); }, updateSelf : function(){ this.fy += this.SPRING_CONSTANT * (this.initHeight - this.height); this.fy *= this.SPRING_FRICTION; this.height += this.fy; }, updateNeighbors : function(){ if(this.previous){ this.force.previous = this.WAVE_SPREAD * (this.height - this.previous.height); } if(this.next){ this.force.next = this.WAVE_SPREAD * (this.height - this.next.height); } }, render : function(context){ if(this.previous){ this.previous.height += this.force.previous; this.previous.fy += this.force.previous; } if(this.next){ this.next.height += this.force.next; this.next.fy += this.force.next; } context.lineTo(this.x, this.renderer.height - this.height); } }; var FISH = function(renderer){ this.renderer = renderer; this.init(); }; FISH.prototype = { GRAVITY : 0.4, init : function(){ this.direction = Math.random() < 0.5; this.x = this.direction ? (this.renderer.width + this.renderer.THRESHOLD) : -this.renderer.THRESHOLD; this.previousY = this.y; this.vx = this.getRandomValue(4, 10) * (this.direction ? -1 : 1); if(this.renderer.reverse){ this.y = this.getRandomValue(this.renderer.height * 1 / 10, this.renderer.height * 4 / 10); this.vy = this.getRandomValue(2, 5); this.ay = this.getRandomValue(0.05, 0.2); }else{ this.y = this.getRandomValue(this.renderer.height * 6 / 10, this.renderer.height * 9 / 10); this.vy = this.getRandomValue(-5, -2); this.ay = this.getRandomValue(-0.2, -0.05); } this.isOut = false; this.theta = 0; this.phi = 0; }, getRandomValue : function(min, max){ return min + (max - min) * Math.random(); }, reverseVertical : function(){ this.isOut = !this.isOut; this.ay *= -1; }, controlStatus : function(context){ this.previousY = this.y; this.x += this.vx; this.y += this.vy; this.vy += this.ay; if(this.renderer.reverse){ if(this.y > this.renderer.height * this.renderer.INIT_HEIGHT_RATE){ this.vy -= this.GRAVITY; this.isOut = true; }else{ if(this.isOut){ this.ay = this.getRandomValue(0.05, 0.2); } this.isOut = false; } }else{ if(this.y < this.renderer.height * this.renderer.INIT_HEIGHT_RATE){ this.vy += this.GRAVITY; this.isOut = true; }else{ if(this.isOut){ this.ay = this.getRandomValue(-0.2, -0.05); } this.isOut = false; } } if(!this.isOut){ this.theta += Math.PI / 20; this.theta %= Math.PI * 2; this.phi += Math.PI / 30; this.phi %= Math.PI * 2; } this.renderer.generateEpicenter(this.x + (this.direction ? -1 : 1) * this.renderer.THRESHOLD, this.y, this.y - this.previousY); if(this.vx > 0 && this.x > this.renderer.width + this.renderer.THRESHOLD || this.vx < 0 && this.x < -this.renderer.THRESHOLD){ this.init(); } }, render : function(context){ context.save(); context.translate(this.x, this.y); context.rotate(Math.PI + Math.atan2(this.vy, this.vx)); context.scale(1, this.direction ? 1 : -1); context.beginPath(); context.moveTo(-30, 0); context.bezierCurveTo(-20, 15, 15, 10, 40, 0); context.bezierCurveTo(15, -10, -20, -15, -30, 0); context.fill(); context.save(); context.translate(40, 0); context.scale(0.9 + 0.2 * Math.sin(this.theta), 1); context.beginPath(); context.moveTo(0, 0); context.quadraticCurveTo(5, 10, 20, 8); context.quadraticCurveTo(12, 5, 10, 0); context.quadraticCurveTo(12, -5, 20, -8); context.quadraticCurveTo(5, -10, 0, 0); context.fill(); context.restore(); context.save(); context.translate(-3, 0); context.rotate((Math.PI / 3 + Math.PI / 10 * Math.sin(this.phi)) * (this.renderer.reverse ? -1 : 1)); context.beginPath(); if(this.renderer.reverse){ context.moveTo(5, 0); context.bezierCurveTo(10, 10, 10, 30, 0, 40); context.bezierCurveTo(-12, 25, -8, 10, 0, 0); }else{ context.moveTo(-5, 0); context.bezierCurveTo(-10, -10, -10, -30, 0, -40); context.bezierCurveTo(12, -25, 8, -10, 0, 0); } context.closePath(); context.fill(); context.restore(); context.restore(); this.controlStatus(context); } }; $(function(){ RENDERER.init(); });