其实在目前的.net4.5框架中已经实现了WebSocket,不用官方实现,我们自己来写个简单的。服务器端需要根据协议来握手、接收和发送。
握手
首先我们再来回顾下握手协议:
关键是服务器端Sec-WebSocket-Accept,它是根据Sec-WebSocket-Key计算出来的:
- 客户端发到服务器的内容:
- GET /chat HTTP/1.1
- Host: server.example.com
- Upgrade: websocket
- Connection: Upgrade
- Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
- Origin: http://example.com
- Sec-WebSocket-Protocol: chat, superchat
- Sec-WebSocket-Version: 13
- 从服务器到客户端的内容:
- HTTP/1.1 101 Switching Protocols
- Upgrade: websocket
- Connection: Upgrade
- Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
- Sec-WebSocket-Protocol: chat
如果握手成功,将会触发客户端的onopen事件。
- /// <summary>
- /// 生成Sec-WebSocket-Accept
- /// </summary>
- /// <param name="handShakeText">客户端握手信息</param>
- /// <returns>Sec-WebSocket-Accept</returns>
- private static string GetSecKeyAccetp(byte[] handShakeBytes,int bytesLength)
- {
- string handShakeText = Encoding.UTF8.GetString(handShakeBytes, 0, bytesLength);
- string key = string.Empty;
- Regex r = new Regex(@"Sec\-WebSocket\-Key:(.*?)\r\n");
- Match m = r.Match(handShakeText);
- if (m.Groups.Count != 0)
- {
- key = Regex.Replace(m.Value, @"Sec\-WebSocket\-Key:(.*?)\r\n", "$1").Trim();
- }
- byte[] encryptionString = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
- return Convert.ToBase64String(encryptionString);
- }
解析接收的客户端信息
接收到客户端数据解析规则如下:
- /// <summary>
- /// 解析客户端数据包
- /// </summary>
- /// <param name="recBytes">服务器接收的数据包</param>
- /// <param name="recByteLength">有效数据长度</param>
- /// <returns></returns>
- private static string AnalyticData(byte[] recBytes, int recByteLength)
- {
- if (recByteLength < 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);
- }
服务器发送的数据以0x81开头,紧接发送内容的长度(若长度在0-125,则1个byte表示长度;若长度不超过0xFFFF,则后2个byte 作为无符号16位整数表示长度;若超过0xFFFF,则后8个byte作为无符号64位整数表示长度),最后是内容的byte数组。
代码如下:
这里只是简单介绍,下节来做个完整的实例。
- /// <summary>
- /// 打包服务器数据
- /// </summary>
- /// <param name="message">数据</param>
- /// <returns>数据包</returns>
- private static byte[] PackData(string message)
- {
- byte[] contentBytes = null;
- byte[] temp = Encoding.UTF8.GetBytes(message);
- if (temp.Length < 126){
- contentBytes = new byte[temp.Length + 2];
- contentBytes[0] = 0x81;
- contentBytes[1] = (byte)temp.Length;
- Array.Copy(temp, 0, contentBytes, 2, temp.Length);
- }else if (temp.Length < 0xFFFF){
- contentBytes = new byte[temp.Length + 4];
- contentBytes[0] = 0x81;
- contentBytes[1] = 126;
- contentBytes[2] = (byte)(temp.Length & 0xFF);
- contentBytes[3] = (byte)(temp.Length >> 8 & 0xFF);
- Array.Copy(temp, 0, contentBytes, 4, temp.Length);
- }else{
- // 暂不处理超长内容
- }
- return contentBytes;
- }