協議 WebSocket是一種基於TCP之上的客戶端與伺服器全雙工通訊的協議,它在HTML5中被定義,也是新一代webapp的基礎規範之一。 它突破了早先的AJAX的限制,關鍵在於實時性,伺服器可以主動推送內容 到客戶端!可能的應用有:多人線上游戲,即時聊天,實時監控,遠程桌面,新聞伺服器等等。 對 ...
協議
WebSocket是一種基於TCP之上的客戶端與伺服器全雙工通訊的協議,它在HTML5中被定義,也是新一代webapp的基礎規範之一。
它突破了早先的AJAX的限制,關鍵在於實時性,伺服器可以主動推送內容 到客戶端!可能的應用有:多人線上游戲,即時聊天,實時監控,遠程桌面,新聞伺服器等等。
對於我自己,當前最想嘗試的是canvas+websocket組合起來能做什麼。
實現
由於握手的過程是一個標準的HTTP請求,因此 websocket 的實現有兩種選擇:1)TCP上實現; 2) 現有HTTP軟體上實現。後者的優勢在於可以共用現有的HTTP伺服器埠,並且不用重新實現認證功能和解析HTTP請求的功能。
這個示例中使用的 node 的HTTP模塊。(TCP版及所有文件見 附件)
node伺服器端代碼:
var http = require('http');
var url = require('url');
// var mime = require('mime');
var crypto = require('crypto');
var port = 4400;
var server = http.createServer();
server.listen(port,function() {
console.log('server is running on localhost:',port);
server
.on('connection',function(s) {
console.log('on connection ',s);
})
.on('request',onrequest)
.on('upgrade',onupgrade);
});
var onrequest = function(req,res) {
console.log( Object.keys(req) ,req.url,req['upgrade']);
if( !req.upgrade ){
// 非upgrade請求選擇:中斷或提供普通網頁
res.writeHead(200, { 'content-type': 'text/plain' });
res.write( 'WebSocket server works!' );
}
res.end();
return;
};
var onupgrade = function (req,sock,head) {
// console.log('方法:',Object.keys(sock));
if(req.headers.upgrade !== 'WebSocket'){
console.warn('非法連接');
sock.end();
return;
}
bind_sock_event(sock);
try{
handshake(req,sock,head);
}catch(e){
console.error(e);
sock.end();
}
};
// 包裝將要發送的幀
var wrap = function(data) {
var fa = 0x00, fe = 0xff, data = data.toString()
len = 2+Buffer.byteLength(data),
buff = new Buffer(len);
buff[0] = fa;
buff.write(data,1);
buff[len-1] = fe;
return buff;
}
// 解開接收到的幀
var unwrap = function(data) {
return data.slice(1,data.length-1);
}
var bind_sock_event = function(sock) {
sock
.on('data',function(buffer) {
var data = unwrap(buffer);
console.log('socket receive data : ',buffer,data,'\n>>> '+data);
// send('hello html5,'+Date.now())
sock.emit('send',data);
})
.on('close',function() {
console.log('socket close');
})
.on('end',function() {
console.log('socket end');
})
.on('send',function(data) { //自定義事件
sock.write(wrap(data),'binary');
})
};
var get_part = function(key) {
var empty = '',
spaces = key.replace(/\S/g,empty).length,
part = key.replace(/\D/g,empty);
if(!spaces) throw {message:'Wrong key: '+key,name:'HandshakeError'}
return get_big_endian(part / spaces);
}
var get_big_endian = function(n) {
return String.fromCharCode.apply(null,[3,2,1,0].map(function(i) { return n >> 8*i & 0xff }))
}
var challenge = function(key1,key2,head) {
var sum = get_part(key1) + get_part(key2) + head.toString('binary');
return crypto.createHash('md5').update(sum).digest('binary');
}
var handshake = function(req,sock,head) {
var output = [],h = req.headers, br = '\r\n';
// header
output.push(
'HTTP/1.1 101 WebSocket Protocol Handshake','Upgrade: WebSocket','Connection: Upgrade',
'Sec-WebSocket-Origin: ' + h.origin,
'Sec-WebSocket-Location: ws://' + h.host + req.url,
'Sec-WebSocket-Protocol: my-custom-chat-protocol'+br
);
// body
var c = challenge(h['sec-websocket-key1'],h['sec-websocket-key2'],head);
output.push(c);
sock.write(output.join(br),'binary');
}
瀏覽器客戶端代碼:
<html>
<head>
<title>WebSocket Demo</title>
</head>
<style type="text/css">
textarea{width:400px;height:150px;display:block;overflow-y:scroll;}
#output{width:600px;height:400px;background:whiteSmoke;padding:1em .5em;color:#000;border:none;}
button{padding:.2em 1em;}
</style>
<link href="layout.css" rel="stylesheet" type="text/css" />
<body>
<textarea id="output" readonly="readonly"></textarea>
<br>
<textarea id="input"></textarea>
<button id="send">send</button>
<script type="text/javascript">
// localhost
var socket = new WebSocket('ws://192.168.144.131:4400/')
socket.onopen = function(e) {
log(e.type);
socket.send('hello node');
}
socket.onclose = function(e) {
log(e.type);
}
socket.onmessage = function(e) {
log('receive @ '+ new Date().toLocaleTimeString() +'\n'+e.data);
output.scrollTop = output.scrollHeight
}
socket.onclose = function(e) {
log(e.type);
}
socket.addEventListener('close',function() {
log('a another close event handler..');
},false);
// dom
var id = function(id) {
return document.getElementById(id);
}
var output = id('output'), input = id('input'), send = id('send');
var log = function(msg) {
output.textContent += '> '+msg + '\n'
}
send.addEventListener('click',function() {
socket.send(input.value);
},false);
</script>
</body>
</html>
細節
在 http 協議之上的 websocket 協議實現只有兩步:握手,發送數據。
握手
握手的過程被稱為 challenge-response。首先客戶端發起一個名為Upgrade的HTTP GET請求,伺服器驗證此請求,給出101響應以表示接受此次協議升級,握手即完成了。
chrome inspector美化過的握手信息:
Request URL:ws://192.168.144.131:4400/pub/chat?q=me
Request Method:GET
Status Code:101 WebSocket Protocol Handshake
Request Headers
Connection:Upgrade
Host:192.168.144.131:4400
Origin:http://localhost:800
Sec-WebSocket-Key1:p2 G 947T 80 661 jAf2
Sec-WebSocket-Key2:z Z Q ^326 5 9= 7s1 1 7H4
Sec-WebSocket-Protocol::my-custom-chat-protocol
Upgrade:WebSocket
(Key3):7C:44:56:CA:1F:19:D2:0A
Response Headers
Connection:Upgrade
Sec-WebSocket-Location:ws://192.168.144.131:4400/pub/chat?q=me
Sec-WebSocket-Origin:http://localhost:800
Sec-WebSocket-Protocol:my-custom-chat-protocol
Upgrade:WebSocket
(Challenge Response):52:DF:2C:F4:50:C2:8E:98:14:B7:7D:09:CF:C8:33:40
請求頭部分
- Host: websocket伺服器主機
- Connection: 連接類型
- Upgrade: 協議升級類型
- Origin: 訪問來源
- Sec-WebSocket-Protocol: 可選,子協議名稱,由應用自己定義,多個協議用空格分割。(*另外一個僅剩的可選項是cookie)
- Sec-WebSocket-Key1: 安全認證key,xhr請求不能偽造'sec-'開頭的請求頭。
- Sec-WebSocket-Key2: 同上
- Key3: 響應體內容,8位元組隨機。
響應頭部分
- Sec-WebSocket-Protocol: 必須包含請求的子協議名
- Sec-WebSocket-Origin: 必須等於請求的來源
- Sec-WebSocket-Location: 必須等於請求的地址
- Challenge Response: 響應體內容,根據請求中三個key計算得來,16位元組。
應答字元串計算過程偽代碼:
part_1 = key1中所有數字 / key1中空格數量
part_2 同上
sum = big_endian(part_1)+big_endian(part_2)+key3
challenge_response = md5_digest(sum);
32位整數的big_endian計算策略:
# 很類似於rgba顏色計算,從下麵的函數可以看出計算過程
var big_endian = function(n) {
return [3,2,1,0].map(function(i) { return n >> 8*i & 0xff });
}
big_endian(0xcc77aaff);
// -> [204, 119, 170, 255]
發送數據
WebSocket API的被設計成用事件處理數據,客戶端只要得到事件通知就可以獲取到完整的數據,而不需要手動處理緩衝器。
這種情況下,每一筆數據被稱為一幀。在規範的定義中,它的頭部必須以0x00開始,尾部屬性以0xff結束,這樣每一次數據發送至少有兩個位元組。
伺服器實現中,收到數據時要截掉頭尾;而發送數據是要包裝頭尾。格式如下:
# '你好'的原始二進位表示,請求頭和這裡都是utf8編碼
<Buffer e4 bd a0 e5 a5 bd>
# 包裝後的二進位表示。
<Buffer 00 e4 bd a0 e5 a5 bd ff>
查看或下載:https://gist.github.com/1066475