转:http://www.cnblogs.com/dolphinX/p/3462898.html
在之前的博客中提到过看到html5 的websocket后很感兴趣,终于可以摆脱长轮询(websocket之前的实现方式可以看看Developer Works上的一篇文章,有简单提到,同时也说了websocket基本概念)等方式做一个山寨版的web聊天室。
什么是websocket
WebSocket 协议是html5引入的一种新的协议,其目的在于实现了浏览器与服务器全双工通信。看了上面链接的同学肯定对过去怎么低效率高消耗(轮询或comet)的做此事已经有所了解了,而在websocket API,浏览器和服务器只需要要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。同时这么做有两个好处
1.通信传输字节减少:比起以前使用http传输数据,websocket传输的额外信息很少,据百度说只有2k
2.服务器可以主动向客户端推送消息,而不用客户端去查询
关于概念和好处,网上到处都是,不再赘述,简单看看其原理,然后动手写一个web版聊天室吧
握手
除了TCP连接的三次握手,websocket协议中客户端与服务器想建立连接需要一次额外的握手动作,在最新版的协议中是这个样子的
客户端向服务器发送请求
GET / HTTP/1.1 Upgrade: websocket Connection: Upgrade Host: 127.0.0.1:8080 Origin: http://test.com Pragma: no-cache Cache-Control: no-cache Sec-WebSocket-Key: OtZtd55qBhJF2XLNDRgUMg== Sec-WebSocket-Version: 13 Sec-WebSocket-Extensions: x-webkit-deflate-frame User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36
服务器给出响应
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: xsOSgr30aKL2GNZKNHKmeT1qYjA=
在请求中的“Sec-WebSocket-Key”是随机的,服务器端会用这些数据来构造出一个SHA-1的信息摘要。把“Sec-WebSocket-Key”加上一个魔幻字符串“258EAFA5-E914-47DA-95CA-C5AB0DC85B11”。使用 SHA-1 加密,之后进行 BASE-64编码,将结果做为 “Sec-WebSocket-Accept” 头的值,返回给客户端(来自维基百科)。
websocket API
经过握手之后浏览器与服务器建立连接,两者就可以互相通信了。websocket的API真心很简单,看看W3C的定义
enum BinaryType { "blob", "arraybuffer" }; [Constructor(DOMString url, optional (DOMString or DOMString[]) protocols)] interface WebSocket : EventTarget { readonly attribute DOMString url; // ready state const unsigned short CONNECTING = 0; const unsigned short OPEN = 1; const unsigned short CLOSING = 2; const unsigned short CLOSED = 3; readonly attribute unsigned short readyState; readonly attribute unsigned long bufferedAmount; // networking attribute EventHandler onopen; attribute EventHandler onerror; attribute EventHandler onclose; readonly attribute DOMString extensions; readonly attribute DOMString protocol; void close([Clamp] optional unsigned short code, optional DOMString reason); // messaging attribute EventHandler onmessage; attribute BinaryType binaryType; void send(DOMString data); void send(Blob data); void send(ArrayBuffer data); void send(ArrayBufferView data); };
创建websocket
ws=new WebSocket(address); //ws://127.0.0.1:8080
调用其构造函数,传入地址,就可以创建一个websocket了,值得注意的是地址协议得是ws/wss
关闭socket
ws.close();
调用webservice实例的close()方法就可以关闭webservice,当然也可以传入一个code和string说明为什么关了
几个回调函数句柄
由于其异步执行,回调函数自然少不了,有四个重要的
- onopen:连接创建后调用
- onmessage:接收到服务器消息后调用
- onerror:出错时调用
- onclose:关闭连接的时候调用
看名字就知道是干什么的了,每个回调函数都会传入一个Event对象,可以通过event.data访问消息
使用API
我们可以在创建socket成功后为其回调函数赋值
ws=new WebSocket(address); ws.onopen=function(e){ var msg=document.createElement('div'); msg.style.color='#0f0'; msg.innerHTML="Server > connection open."; msgContainer.appendChild(msg); ws.send('{<'+document.getElementById('name').value+'>}'); };
也可以通过事件绑定的方式
ws=new WebSocket(address); ws.addEventListener('open',function(e){ var msg=document.createElement('div'); msg.style.color='#0f0'; msg.innerHTML="Server > connection open."; msgContainer.appendChild(msg); ws.send('{<'+document.getElementById('name').value+'>}'); });
客户端实现
其实客户端的实现比较简单,除了websocket相关的几句就是一些自动focus、回车键事件处理、消息框自动定位到底部等简单功能,不一一说明了
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>Web Socket Client</title> 5 </head> 6 <body style="padding:10px;"> 7 <h1>Web Socket Chating Room</h1> 8 <div style="margin:5px 0px;"> 9 Address: 10 <div><input id="address" type="text" value="ws://127.0.0.1:8080" style="400px;"/></div> 11 </div> 12 <div style="margin:5px 0px;"> 13 Name: 14 <div><input id="name" type="text" value="Byron" style="400px;"/></div> 15 </div> 16 <div> 17 <button id="connect" onclick="connect();">connect server</button> 18 <button id="disconnect" onclick="quit();">disconnect</button> 19 <button id="clear" onclick="clearMsg();">clear</button> 20 </div> 21 <h5 style="margin:4px 0px;">Message:</h5> 22 <div id="message" style="border:solid 1px #333; padding:4px; 400px; overflow:auto; 23 height:300px; margin-bottom:8px; font-size:14px;"> 24 </div> 25 <input id="text" type="text" onkeypress="enter(event);" style="340px"/> 26 <button id="send" onclick="send();">send</button> 27 28 <script type="text/javascript"> 29 var name=document.getElementById('name').value; 30 var msgContainer=document.getElementById('message'); 31 var text=document.getElementById('text'); 32 33 function connect () { 34 var address=document.getElementById('address').value; 35 36 ws=new WebSocket(address); 37 ws.onopen=function(e){ 38 var msg=document.createElement('div'); 39 msg.style.color='#0f0'; 40 msg.innerHTML="Server > connection open."; 41 msgContainer.appendChild(msg); 42 ws.send('{<'+document.getElementById('name').value+'>}'); 43 }; 44 ws.onmessage=function(e){ 45 var msg=document.createElement('div'); 46 msg.style.color='#fff'; 47 msg.innerHTML=e.data; 48 msgContainer.appendChild(msg); 49 }; 50 ws.onerror=function(e){ 51 var msg=document.createElement('div'); 52 msg.style.color='#0f0'; 53 msg.innerHTML='Server > '+e.data; 54 msgContainer.appendChild(msg); 55 }; 56 ws.onclose=function(e){ 57 var msg=document.createElement('div'); 58 msg.style.color='#0f0'; 59 msg.innerHTML="Server > connection closed by server."; 60 msgContainer.appendChild(msg); 61 }; 62 text.focus(); 63 } 64 65 function quit(){ 66 if(ws){ 67 ws.close(); 68 var msg=document.createElement('div'); 69 msg.style.color='#0f0'; 70 msg.innerHTML='Server > connection closed.'; 71 msgContainer.appendChild(msg); 72 ws=null; 73 } 74 } 75 76 function send(){ 77 ws.send(text.value); 78 setTimeout(function(){ 79 msgContainer.scrollTop=msgContainer.getBoundingClientRect().height; 80 },100); 81 text.value=''; 82 text.focus(); 83 } 84 85 function clearMsg(){ 86 msgContainer.innerHTML=""; 87 } 88 89 function enter(event){ 90 if(event.keyCode==13){ 91 send(); 92 } 93 } 94 </script> 95 </body> 96 </html>
服务器支持
其实websocket的服务器实现网上可以找到很多了,向维基百科中列出的
- php - http://code.google.com/p/phpwebsocket/
- jetty - http://jetty.codehaus.org/jetty/ (版本7开始支持websocket)
- netty - http://www.jboss.org/netty
- ruby - http://github.com/gimite/web-socket-ruby
- Kaazing - http://www.kaazing.org/confluence/display/KAAZING/Home
- Tomcat - http://tomcat.apache.org/ (7.0.26支持websocket)
- WebLogic - http://www.oracle.com/us/products/middleware/cloud-app-foundation/weblogic/overview/index.html (12.1.2 开始支持)
- node.js - https://github.com/Worlize/WebSocket-Node
- node.js - http://socket.io
- nginx - http://nginx.com/
- mojolicious - http://mojolicio.us/
但是我希望加入一些自己特定的处理,比如用户名识别啊、广播啊什么的,所以自己实现了一个简单的C#版本
websocket 聊天室C#服务器实现
我上篇博客C# socket编程实践——支持广播的简单socket服务器中介绍了怎么实现一个简单的C#广播服务器,在这上面扩展两个部分就能作为websocket服务器了
1.wecsocket握手处理
当服务器收到浏览器握手请求后,首先需要识别握手信息,我简单粗暴的使用了包含字符串处理,当然加入了是否握过手的判断
client.BeginReceive (buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback (Recieve), client); string msg = Encoding.UTF8.GetString (buffer, 0, length); if (!clientPool [client].IsHandShaked && msg.Contains ("Sec-WebSocket-Key")) { client.Send (PackageHandShakeData (buffer, length)); clientPool [client].IsHandShaked = true; return; }
识别成功后就可以生成服务器响应发送给客户端了
/// <summary> /// 打包服务器握手数据 /// </summary> /// <returns>The hand shake data.</returns> /// <param name="handShakeBytes">Hand shake bytes.</param> /// <param name="length">Length.</param> private byte[] PackageHandShakeData (byte[] handShakeBytes, int length) { string handShakeText = Encoding.UTF8.GetString (handShakeBytes, 0, length); string key = string.Empty; Regex reg = new Regex (@"Sec-WebSocket-Key:(.*?) "); Match m = reg.Match (handShakeText); if (m.Value != "") { key = Regex.Replace (m.Value, @"Sec-WebSocket-Key:(.*?) ", "$1").Trim (); } byte[] secKeyBytes = SHA1.Create ().ComputeHash ( Encoding.ASCII.GetBytes (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")); string secKey = Convert.ToBase64String (secKeyBytes); var responseBuilder = new StringBuilder (); responseBuilder.Append ("HTTP/1.1 101 Switching Protocols" + " "); responseBuilder.Append ("Upgrade: websocket" + " "); responseBuilder.Append ("Connection: Upgrade" + " "); responseBuilder.Append ("Sec-WebSocket-Accept: " + secKey + " "); return Encoding.UTF8.GetBytes (responseBuilder.ToString ()); }
2.解析浏览器消息和处理发送给浏览器的消息
websocket中数据并不完全是消息本身,我们需要做一些处理
/// <summary> /// 解析客户端发送来的数据 /// </summary> /// <returns>The data.</returns> /// <param name="recBytes">Rec bytes.</param> /// <param name="length">Length.</param> private string AnalyzeClientData (byte[] recBytes, int length) { if (length < 2) { return string.Empty; } bool fin = (recBytes [0] & 0x80) == 0x80; // 1bit,1表示最后一帧 if (!fin) { return string.Empty;// 超过一帧暂不处理 } bool mask_flag = (recBytes [1] & 0x80) == 0x80; // 是否包含掩码 if (!mask_flag) { return string.Empty;// 不包含掩码的暂不处理 } int payload_len = recBytes [1] & 0x7F; // 数据长度 byte[] masks = new byte[4]; byte[] payload_data; if (payload_len == 126) { Array.Copy (recBytes, 4, masks, 0, 4); payload_len = (UInt16)(recBytes [2] << 8 | recBytes [3]); payload_data = new byte[payload_len]; Array.Copy (recBytes, 8, payload_data, 0, payload_len); } else if (payload_len == 127) { Array.Copy (recBytes, 10, masks, 0, 4); byte[] uInt64Bytes = new byte[8]; for (int i = 0; i < 8; i++) { uInt64Bytes [i] = recBytes [9 - i]; } UInt64 len = BitConverter.ToUInt64 (uInt64Bytes, 0); payload_data = new byte[len]; for (UInt64 i = 0; i < len; i++) { payload_data [i] = recBytes [i + 14]; } } else { Array.Copy (recBytes, 2, masks, 0, 4); payload_data = new byte[payload_len]; Array.Copy (recBytes, 6, payload_data, 0, payload_len); } for (var i = 0; i < payload_len; i++) { payload_data [i] = (byte)(payload_data [i] ^ masks [i % 4]); } return Encoding.UTF8.GetString (payload_data); }
/// <summary> /// 把客户端消息打包处理(拼接上谁什么时候发的什么消息) /// </summary> /// <returns>The data.</returns> /// <param name="message">Message.</param> private byte[] PackageServerData (SocketMessage sm) { StringBuilder msg = new StringBuilder (); if (!sm.isLoginMessage) { //消息是login信息 msg.AppendFormat ("{0} @ {1}: ", sm.Client.Name, sm.Time.ToShortTimeString ()); msg.Append (sm.Message); } else { //处理普通消息 msg.AppendFormat ("{0} login @ {1}", sm.Client.Name, sm.Time.ToShortTimeString ()); } byte[] content = null; byte[] temp = Encoding.UTF8.GetBytes (msg.ToString ()); if (temp.Length < 126) { content = new byte[temp.Length + 2]; content [0] = 0x81; content [1] = (byte)temp.Length; Array.Copy (temp, 0, content, 2, temp.Length); } else if (temp.Length < 0xFFFF) { content = new byte[temp.Length + 4]; content [0] = 0x81; content [1] = 126; content [2] = (byte)(temp.Length & 0xFF); content [3] = (byte)(temp.Length >> 8 & 0xFF); Array.Copy (temp, 0, content, 4, temp.Length); } else { // 暂不处理超长内容 } return content; }
如果看不懂我在写什么,并且对C#版websocket感兴趣的同学需要看一下我上一篇博客了
有图有真相
看看我们写的聊天室运行效果吧
服务器
客户端——Byron
客户端——Casper
源代码
源代码我已经上传到了我的github上,对github不感冒的同学可以直接点击这里下载,有兴趣的同学可以下载看看,因为我在Mac+mono+Xamarin Studio上开发的(忽然感觉自己好极品在Mac上用C#。。。),所以代码编码和Windows可能会有些差距,改成Windows兼容的应该就可以直接运行了,不过没在Window下跑过,如果有错误还请大家多多指正。