WebSocket 是一種網絡通訊協議。RFC6455 定義了它的通訊標準。css
WebSocket 是 HTML5 開始提供的一種在單個 TCP 鏈接上進行全雙工通信的協議。html
瞭解計算機網絡協議的人,應該都知道:HTTP 協議是一種無狀態的、無鏈接的、單向的應用層協議。它採用了請求/響應模型。通訊請求只能由客戶端發起,服務端對請求作出應答處理。前端
這種通訊模型有一個弊端:HTTP 協議沒法實現服務器主動向客戶端發起消息。jquery
這種單向請求的特色,註定了若是服務器有連續的狀態變化,客戶端要獲知就很是麻煩。大多數 Web 應用程序將經過頻繁的異步JavaScript和XML(AJAX)請求實現長輪詢。輪詢的效率低,很是浪費資源(由於必須不停鏈接,或者 HTTP 鏈接始終打開)。web
Web瀏覽器和服務器都必須實現 WebSockets 協議來創建和維護鏈接。因爲 WebSockets 鏈接長期存在,與典型的HTTP鏈接不一樣,對服務器有重要的影響。django
基於多線程或多進程的服務器沒法適用於 WebSockets,由於它旨在打開鏈接,儘量快地處理請求,而後關閉鏈接。任何實際的 WebSockets 服務器端實現都須要一個異步服務器。json
-服務端(socket服務器)
1.服務器開啓socket,監聽ip和端口
3.容許鏈接
* 5.服務端收到特殊值【特殊值加密sha1,migic string="258EAFA5-E914-47DA-95CA-C5AB0DC85B11"】
* 6.加密後的值發送給客戶端
-客戶端(瀏覽器)
2.客戶端發起鏈接請求(ip和端口)
* 4.客戶端生成一個隨機字符串xxx,【特殊值加密sha1,migic string="258EAFA5-E914-47DA-95CA-C5AB0DC85B11"】,向服務端發送一段特殊值
* 7.客戶端收到加密的值
***收發數據***
""" 1.位運算,右移動 10010001 右4 00001001 左4 100100010000 2.異或運算 1,1:1 0,1 :0 0,0 :0 查看某個數的後四位 10001010 00001111 00001010 info = b'\x81\x8b\xc9\x11\x81b\xa1t\xed\x0e\xa61\xf6\r\xbb}\xe5' opcode = info[0] & 15 獲取第一個字節的後四位 fin = info[0] >> 7 payload_len = info[1] & 127 if payload_len<126: 頭部佔2個字節 elif payload_len == 126: 頭部佔4個字節 else: 頭部佔10個字節 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-------+-+-------------+-------------------------------+ |F|R|R|R| opcode|M| Payload len | Extended payload length | |I|S|S|S| (4) |A| (7) | (16/64) | |N|V|V|V| |S| | (if payload len==126/127) | | |1|2|3| |K| | | +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + | Extended payload length continued, if payload len == 127 | + - - - - - - - - - - - - - - - +-------------------------------+ | |Masking-key, if MASK set to 1 | +-------------------------------+-------------------------------+ | Masking-key (continued) | Payload Data | +-------------------------------- - - - - - - - - - - - - - - - + : Payload Data continued ... : + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + | Payload Data continued ... | +------------------------------------------------------------
在客戶端,沒有必要爲 WebSockets 使用 JavaScript 庫。實現 WebSockets 的 Web 瀏覽器將經過 WebSockets 對象公開全部必需的客戶端功能(主要指支持 Html5 的瀏覽器)。flask
如下 API 用於建立 WebSocket 對象。bootstrap
所以,工程師們一直在思考,有沒有更好的方法。WebSocket 就是這樣發明的。WebSocket 鏈接容許客戶端和服務器之間進行全雙工通訊,以便任一方均可以經過創建的鏈接將數據推送到另外一端。WebSocket 只須要創建一次鏈接,就能夠一直保持鏈接狀態。這相比於輪詢方式的不停創建鏈接顯然效率要大大提升。後端
var Socket = new WebSocket(url, [protocol] );
如下是 WebSocket 對象的屬性。假定咱們使用了以上代碼建立了 Socket 對象:
如下是 WebSocket 對象的相關事件。假定咱們使用了以上代碼建立了 Socket 對象:
如下是 WebSocket 對象的相關方法。假定咱們使用了以上代碼建立了 Socket 對象:
示例一:websocket+tornado實現聊天室
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body{ background-color: black; } .container{ border:2px solid #dddddd; height: 400px; overflow: auto; } </style> </head> <body> <div style="width: 750px;margin: 0 auto;background-color: #dddddd"> <h1 style="background-color: lawngreen">1024聊天室</h1> <div class="container"></div> <div class="input"> <input class="name" style="width: 50px;height: 15px;" type="text" value="遊客"> <input type="text" id="txt"> <input type="button" id="btn" value="發送" onclick="sendMessage()"> <input type="button" id="close" value="關閉鏈接" onclick="closeConn()"/> </div> <div id="content"></div> </div> <script src="/static/jquery-2.1.4.min.js"></script> <script> $(function () { wsUpdater.start(); }); var wsUpdater = { socket: null, name: null, start: function() { var url = "ws://127.0.0.1:8888/chat"; wsUpdater.socket = new WebSocket(url); wsUpdater.socket.onopen = function () { /* 與服務器端鏈接成功後,自動執行 */ var newTag = document.createElement('div'); newTag.innerHTML = "【鏈接成功】"; document.getElementById('content').appendChild(newTag); }; wsUpdater.socket.onmessage = function(event) { console.log(event); if(wsUpdater.name){ wsUpdater.showMessage(event.data); }else{ wsUpdater.name = event.data; } } }, showMessage: function(content) { $('.container').append(content); } }; function closeConn() { /* 服務器端主動斷開鏈接時,自動執行 */ if (confirm("您肯定要關閉本頁嗎?")){ // 舊方法 {#window.opener=null;#} {#window.open('','_self');#} {#window.close();#} // 新方法 window.location.href="about:blank"; window.close(); } else{} }; $("#txt").keydown(function (e) {//當按下按鍵時 if (e.which == 13) {//.which屬性判斷按下的是哪一個鍵,回車鍵的鍵位序號爲13 $('#btn').trigger("click");//觸發搜索按鈕的點擊事件 } }); function sendMessage() { var msg = { name:$(".name").val(), message: $("#txt").val() }; wsUpdater.socket.send(JSON.stringify(msg)); } </script> </body> </html>
# -*- coding: utf-8 -*-
"""
@Datetime: 2018/8/28
@Author: Zhang Yafei
"""
import json
import uuid
import tornado.web
import tornado.ioloop
import tornado.websocket
class IndexHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
self.render('index.html')
class ChatHandler(tornado.websocket.WebSocketHandler):
users = set()
messages = []
def open(self, *args, **kwargs):
"""
客戶端和服務器已經創建鏈接
1.鏈接
2.握手
:param args:
:param kwargs:
:return:
"""
ChatHandler.users.add(self)
# uid = str(uuid.uuid4())
# self.write_message(uid)
# for msg in ChatHandler.messages:
# content = self.render_string('message.html', **msg)
# self.write_message(content)
def on_message(self, message):
msg = json.loads(message)
ChatHandler.messages.append(message)
for client in ChatHandler.users:
content = self.render_string('message.html',**msg)
client.write_message(content)
def on_close(self):
"""
客戶端主動關閉鏈接
:return:
"""
ChatHandler.users.remove(self)
def run():
settings = {
'template_path': 'templates',
'static_path': 'static',
}
application = tornado.web.Application([
(r"/", IndexHandler),
(r"/chat", ChatHandler),
], **settings)
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
run()
1024聊天室效果圖
示例二:websocket+flask實現實時投票系統
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3個meta標籤*必須*放在最前面,任何其餘內容都*必須*跟隨其後! --> <meta name="description" content=""> <meta name="author" content=""> <title>投票系統</title> <!-- Bootstrap core CSS --> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <link href="static/css/ie10-viewport-bug-workaround.css" rel="stylesheet"> <link href="static/plugins/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="static/css/dashboard.css" rel="stylesheet"> <script src="static/js/ie-emulation-modes-warning.js"></script> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">投票系統</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a class="item" href="#">消息<i style="margin-left: 3px;" class="fa fa-bell-o" aria-hidden="true"></i> <span class="badge" style="background-color: red">4</span></a> </li> <li><a class="item" href="#">通知<i style="margin-left: 3px;" class="fa fa-envelope-o" aria-hidden="true"></i> <span class="badge" style="background-color:forestgreen">4</span></a> </li> <li><a class="item" href="#">任務<i style="margin-left: 3px;" class="fa fa-commenting-o" aria-hidden="true"></i> <span class="badge" style="background-color: forestgreen">4</span></a> </li> <li><a href="https://v3.bootcss.com/examples/dashboard/#"></a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">張亞飛 <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">我的信息</a></li> <li><a href="#">退出</a></li> </ul> </li> </ul> <form class="navbar-form navbar-right"> <input type="text" class="form-control" placeholder="Search..."> </form> </div> </div> </nav> <div class="row"> <div class="col-sm-3 col-md-2 sidebar"> <ul class="nav nav-sidebar"> <li class="active"><a href="#">投票系統<span class="sr-only">(current)</span></a></li> </ul> </div> <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> <h1 class="page-header">候選人</h1> <button style="position: absolute;right: 115px;top: 25px;" class="btn btn-success" onclick="closeConn()">關閉鏈接 </button> <ul id="userList" class="row placeholders"> {% for key,val in users.items() %} <div class="col-xs-6 col-sm-3 placeholder"> <img src="{{ val['image'] }}" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail"> <h4> {{ val['name'] }} <span class="badge" id="id_{{ key }}" style="background-color: red">{{ val['count'] }}</span> </a> </h4> <li onclick="vote({{ key }})" class="text-muted btn btn-primary">投票</li> </div> {% endfor %} </ul> </div> </div> </div> </div> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"><\/script>')</script> <script src="https://cdn.bootcss.com/twitter-bootstrap/4.2.1/js/bootstrap.min.js"></script> <!-- Just to make our placeholder images work. Don't actually copy the next line! --> <script src="static/js/holder.min.js"></script> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <script src="static/js/ie10-viewport-bug-workaround.js"></script> <script> var ws = new WebSocket('ws://192.168.43.254:5000/message') ws.onmessage = function (event) { /* 服務器端向客戶端發送數據時,自動執行 */ // {'cid':cid,'count':new} var response = JSON.parse(event.data); $('#id_' + response.cid).text(response.count); }; function vote(cid) { ws.send(cid); } function closeConn() { /* 服務器端主動斷開鏈接時,自動執行 */ if (confirm("您肯定要關閉本頁嗎?")){ window.location.href="about:blank"; window.close(); } else{} }; </script> </body> </html>
# -*- coding: utf-8 -*- """ @Datetime: 2019/1/9 @Author: Zhang Yafei """ from flask import Flask,render_template,request from geventwebsocket.handler import WebSocketHandler from gevent.pywsgi import WSGIServer import json app = Flask(__name__) USERS = { '1':{'name':'姚明','count':1,'image':'static/images/姚明.jpg'}, '2':{'name':'詹姆斯','count':0,'image':'static/images/詹姆斯.jpg'}, '3':{'name':'科比','count':0,'image':'static/images/科比.jpg'}, } # http://127.0.0.1:5000/index @app.route('/index') def index(): return render_template('home.html',users=USERS) # http://127.0.0.1:5000/message WEBSOCKET_LIST = [] @app.route('/message') def message(): ws = request.environ.get('wsgi.websocket') # ws爲空表示http請求,不然爲websocket請求 if not ws: print('http') return '您使用的是Http協議' WEBSOCKET_LIST.append(ws) while True: cid = ws.receive() if not cid: WEBSOCKET_LIST.remove(ws) ws.close() break old = USERS[cid]['count'] new = old + 1 USERS[cid]['count'] = new for client in WEBSOCKET_LIST: client.send(json.dumps({'cid':cid,'count':new})) if __name__ == '__main__': # http協議走app, websocket協議走websocket http_server = WSGIServer(('0.0.0.0', 80), app, handler_class=WebSocketHandler) http_server.serve_forever()
投票系統效果圖
手動實現websocket
# -*- coding: utf-8 -*- """ @Datetime: 2018/8/28 @Author: Zhang Yafei """ import base64 import hashlib import socket import struct def send_msg(conn, msg_bytes): token = b"\x81" length = len(msg_bytes) if length < 126: token += struct.pack("B", length) elif length <= 0xFFFF: token += struct.pack("!BH", 126, length) else: token += struct.pack("!BQ", 127, length) msg = token + msg_bytes conn.send(msg) return True def get_headers(data): """ 將請求頭格式化成字典 :param data: :return: """ header_dict = {} data = str(data, encoding='utf-8') header, body = data.split('\r\n\r\n', 1) header_list = header.split('\r\n') for i in range(0, len(header_list)): if i == 0: if len(header_list[i].split(' ')) == 3: header_dict['method'], header_dict['url'], header_dict['protocol'] = header_list[i].split(' ') else: k, v = header_list[i].split(':', 1) header_dict[k] = v.strip() return header_dict sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) sock.bind(('127.0.0.1',8002)) sock.listen(5) #等待用戶鏈接 conn,address = sock.accept() #握手消息 data = conn.recv(8096) headers = get_headers(data) # for k,v in headers.items(): # print(k,v) magic_string = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" value = headers['Sec-WebSocket-Key'] + magic_string ac = base64.b64encode(hashlib.sha1(value.encode('utf-8')).digest()) response_tpl = "HTTP/1.1 101 Switching Protocols\r\n" \ "Upgrade:websocket\r\n" \ "Connection:Upgrade\r\n" \ "Sec-WebSocket-Accept:%s\r\n" \ "WebSocket-Location:ws://%s%s\r\n\r\n" #獲取握手消息,magic string.sha1加密 #發送回客戶端 response_str = response_tpl % (ac.decode('utf-8'), headers['Host'], headers['url']) conn.send(bytes(response_str, encoding='utf-8')) while True: info = conn.recv(8096) payload_len = info[1] & 127 if payload_len == 126: extend_payload_len = info[2:4] mask = info[4:8] decoded = info[8:] elif payload_len == 127: extend_payload_len = info[2:10] mask = info[10:14] decoded = info[14:] else: extend_payload_len = None mask = info[2:6] decoded = info[6:] bytes_list = bytearray() for i in range(len(decoded)): chunk = decoded[i] ^ mask[i % 4] bytes_list.append(chunk) body = str(bytes_list, encoding='utf-8') body = body + '見到你很開心!' send_msg(conn,bytes(body,encoding='utf-8'))
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> ws = new WebSocket("ws://127.0.0.1:8002"); ws.onopen = function () { console.log('1111'); ws.send('hello 張亞飛') }; ws.onmessage = function (event) { console.log(event); }; ws.onclose = function () { } </script> </body> </html>
知識點
1. 什麼是websocket?
是一套協議,協議規定了:
- 鏈接時須要握手
- 發送數據進行加密
- 鏈接以後不斷開
2. websocket的意義?
實現服務段想客戶端主動推送消息,實時通信
3. websocket的兼容性是他的缺點。
4. 哪些框架支持websocket?
- flask,gevent-websocket
- django,channel
- torando框架自帶
5. 應用場景?
實時響應頁面時,可使用websocket。
6. websocket實現原理
websocket原理: 1. 服務端運行,等待客戶端鏈接 2. 小強來鏈接,服務端贊成。 3. 小強當即發送一個「握手信息」 GET /xxxx HTTP/1.1\r\n Host: 127.0.0.1:8002\r\n Connection: Upgrade\r\n Pragma: no-cache\r\n Cache-Control: no-cache\r\n Upgrade: websocket\r\n Origin: http://localhost:63342\r\nSec-WebSocket-Version: 13\r\n User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36\r\n Accept-Encoding: gzip, deflate, br\r\n Accept-Language: zh-CN,zh;q=0.9\r\n Cookie: csrftoken=ojyruuaF3Tk0OToIrXy1sRSdSk3SeDgd6Ti3jocEXAuEExaMtxjhJglpenj6Iq8F\r\n Sec-WebSocket-Key: 4NZY2fTOr691upgWe2yq7w==\r\n ######## 這裏 ######## Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits\r\n\r\n 4. 服務端接收握手信息後須要對數據進行加密,給客戶端返回 - 4NZY2fTOr691upgWe2yq7w + magic_string - sha1 - base64 response_tpl = "HTTP/1.1 101 Switching Protocols\r\n" \ "Upgrade:websocket\r\n" \ "Connection: Upgrade\r\n" \ "Sec-WebSocket-Accept: 加密以後的結果\r\n" \ "WebSocket-Location: ws://127.0.0.1:8002\r\n\r\n" 雙方能夠進行互相通訊: 5. 小強給服務端發送消息: 讀取第二個字節的後7位 127:10,4,數據 126:4,4,數據 <=125: 2,4,數據 6. 服務端給客戶端發送消息: token = b"\x81" length = len(msg_bytes) if length < 126: token += struct.pack("B", length) elif length <= 0xFFFF: token += struct.pack("!BH", 126, length) else: token += struct.pack("!BQ", 127, length)