HTML 5 WebSocket實現實時視頻文字傳輸(2)

客戶端

在支持WebSocket的瀏覽器中,可以直接在Javascript中通過WebSocket對象來實現通信。WebSocket對象主要通過onopen,onmessage,onclose即onerror四個事件實現對socket消息的異步響應。

請創建靜態頁面 不用創建ruant=“server”的 否則會自動reload

  1. <!DOCTYPE html> 
  2.  
  3. <html xmlns="http://www.w3.org/1999/xhtml"> 
  4. <head> 
  5.     <title></title> 
  6.     <script type="text/javascript"> 
  7.         var wsServer = 'ws://localhost:9999/webSocket.ashx'; //基於.NET4.5服務器地址  
  8.         //var wsServer = 'ws://localhost:1818'; //基於.NET服務器地址  
  9.  
  10.         var websocket = new WebSocket(wsServer); //創建WebSocket對象  
  11.         //websocket.send("hello");//向服務器發送消息  
  12.         //alert(websocket.readyState);//查看websocket當前狀態  
  13.         websocket.onopen = function (evt) {  
  14.             //已經建立連接  
  15.             alert("已經建立連接");  
  16.         };  
  17.         websocket.onclose = function (evt) {  
  18.             //已經關閉連接  
  19.             alert("已經關閉連接");  
  20.         };  
  21.         websocket.onmessage = function (evt) {  
  22.             //收到服務器消息,使用evt.data提取  
  23.             evt.stopPropagation()  
  24.             evt.preventDefault()  
  25.             //alert(evt.data);  
  26.             writeToScreen(evt.data);  
  27.             //websocket.close();  
  28.         };  
  29.         websocket.onerror = function (evt) {  
  30.             //產生異常  
  31.             //alert(evt.message);  
  32.             writeToScreen(evt.message);  
  33.         };  
  34.         function sendMsg() {  
  35.             if (websocket.readyState == websocket.OPEN) {  
  36.                 msg = document.getElementById("msg").value;  
  37.                 websocket.send(msg);  
  38.                 writeToScreen("發送成功!");  
  39.             } else {  
  40.                 writeToScreen("連接失敗!");  
  41.             }  
  42.         }  
  43.  
  44.         function writeToScreen(message) {  
  45.             var pre = document.createElement("p");  
  46.             pre.style.wordWrap = "break-word";  
  47.             pre.innerHTML += message;  
  48.             output.appendChild(pre);  
  49.         }  
  50.     </script> 
  51. </head> 
  52. <body> 
  53.     <div> 
  54.         <input type="text" id="msg" value="beyond is number one!" /> 
  55.         <button onclick="sendMsg()">send</button> 
  56.     </div> 
  57.     <div id="output"></div> 
  58. </body> 
  59. </html> 

readyState表示連接有四種狀態:

CONNECTING (0):表示還沒建立連接;

OPEN (1): 已經建立連接,可以進行通訊;

CLOSING (2):通過關閉握手,正在關閉連接;

CLOSED (3):連接已經關閉或無法打開;

url是代表 WebSocket 服務器的網絡地址,協議通常是”ws”或“wss(加密通信)”,send 方法就是發送數據到服務器端;

close 方法就是關閉連接;

onopen連接建立,即握手成功觸發的事件;

onmessage收到服務器消息時觸發的事件;

onerror異常觸發的事件;

onclose關閉連接觸發的事件;

先說說基於.NET4.5的吧 ashx裏面應該是這樣寫的

  1. //得到當前WebSocket請求  
  2.             HttpContext.Current.AcceptWebSocketRequest(async (context) =>  
  3.             {  
  4.                 WebSocket socket = context.WebSocket;//Socket  
  5.                 while (true)  
  6.                 {  
  7.                     ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);  
  8.                     CancellationToken token;  
  9.                     WebSocketReceiveResult result =  
  10.                             await socket.ReceiveAsync(buffer, token);  
  11.                     if (socket.State == WebSocketState.Open)  
  12.                     {  
  13.                         string userMessage = Encoding.UTF8.GetString(buffer.Array, 0,  
  14.                                 result.Count);  
  15.                         userMessage = "You sent: " + userMessage + " at " +  
  16.                                 DateTime.Now.ToLongTimeString();  
  17.                         buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMessage));  
  18.                         await socket.SendAsync(buffer, WebSocketMessageType.Text,  
  19.                                 true, CancellationToken.None);  
  20.                     }  
  21.                     else { break; }  
  22.                 }  
  23.             }); 

然後需要注意的是 部署到IIS8上面  轉到 Windows程序和功能 -打開Windows功能裏面 IIS選項啓動4.5 和WebSocket支持  否則會報錯誤的。

如果你不是Windows8 或者IIS的問題 你可以使用其他方式實現websocket服務器 比如.net socket模擬(因爲websocket本身就是基於TCP的完全可以模擬只是規則特別..)

網上有人寫了下面一段

  1. class Program  
  2.   {  
  3.       static void Main(string[] args)  
  4.       {  
  5.           int port = 1818;  
  6.           byte[] buffer = new byte[1024];  
  7.  
  8.           IPEndPoint localEP = new IPEndPoint(IPAddress.Any, port);  
  9.           Socket listener = new Socket(localEP.Address.AddressFamily,SocketType.Stream, ProtocolType.Tcp);  
  10.             
  11.           try{  
  12.               listener.Bind(localEP);  
  13.               listener.Listen(10);  
  14.  
  15.               Console.WriteLine("等待客戶端連接....");  
  16.               Socket sc = listener.Accept();//接受一個連接  
  17.               Console.WriteLine("接受到了客戶端:"+sc.RemoteEndPoint.ToString()+"連接....");  
  18.                 
  19.               //握手  
  20.               int length = sc.Receive(buffer);//接受客戶端握手信息  
  21.               sc.Send(PackHandShakeData(GetSecKeyAccetp(buffer,length)));  
  22.               Console.WriteLine("已經發送握手協議了....");  
  23.                 
  24.               //接受客戶端數據  
  25.               Console.WriteLine("等待客戶端數據....");  
  26.               length = sc.Receive(buffer);//接受客戶端信息  
  27.               string clientMsg=AnalyticData(buffer, length);  
  28.               Console.WriteLine("接受到客戶端數據:" + clientMsg);  
  29.  
  30.               //發送數據  
  31.               string sendMsg = "您好," + clientMsg;  
  32.               Console.WriteLine("發送數據:“"+sendMsg+"” 至客戶端....");  
  33.               sc.Send(PackData(sendMsg));  
  34.                 
  35.               Console.WriteLine("演示Over!");  
  36.  
  37.           }  
  38.           catch (Exception e)  
  39.           {  
  40.               Console.WriteLine(e.ToString());  
  41.           }  
  42.       }  
  43.  
  44.       /// <summary>  
  45.       /// 打包握手信息  
  46.       /// </summary>  
  47.       /// <param name="secKeyAccept">Sec-WebSocket-Accept</param>  
  48.       /// <returns>數據包</returns>  
  49.       private static byte[] PackHandShakeData(string secKeyAccept)  
  50.       {  
  51.           var responseBuilder = new StringBuilder();  
  52.           responseBuilder.Append("HTTP/1.1 101 Switching Protocols" + Environment.NewLine);  
  53.           responseBuilder.Append("Upgrade: websocket" + Environment.NewLine);  
  54.           responseBuilder.Append("Connection: Upgrade" + Environment.NewLine);  
  55.           responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine + Environment.NewLine);  
  56.           //如果把上一行換成下面兩行,纔是thewebsocketprotocol-17協議,但居然握手不成功,目前仍沒弄明白!  
  57.           //responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine);  
  58.           //responseBuilder.Append("Sec-WebSocket-Protocol: chat" + Environment.NewLine);  
  59.  
  60.           return Encoding.UTF8.GetBytes(responseBuilder.ToString());  
  61.       }  
  62.  
  63.       /// <summary>  
  64.       /// 生成Sec-WebSocket-Accept  
  65.       /// </summary>  
  66.       /// <param name="handShakeText">客戶端握手信息</param>  
  67.       /// <returns>Sec-WebSocket-Accept</returns>  
  68.       private static string GetSecKeyAccetp(byte[] handShakeBytes,int bytesLength)  
  69.       {  
  70.           string handShakeText = Encoding.UTF8.GetString(handShakeBytes, 0, bytesLength);  
  71.           string key = string.Empty;  
  72.           Regex r = new Regex(@"Sec\-WebSocket\-Key:(.*?)\r\n");  
  73.           Match m = r.Match(handShakeText);  
  74.           if (m.Groups.Count != 0)  
  75.           {  
  76.               key = Regex.Replace(m.Value, @"Sec\-WebSocket\-Key:(.*?)\r\n""$1").Trim();  
  77.           }  
  78.           byte[] encryptionString = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));  
  79.           return Convert.ToBase64String(encryptionString);  
  80.       }  
  81.  
  82.       /// <summary>  
  83.       /// 解析客戶端數據包  
  84.       /// </summary>  
  85.       /// <param name="recBytes">服務器接收的數據包</param>  
  86.       /// <param name="recByteLength">有效數據長度</param>  
  87.       /// <returns></returns>  
  88.       private static string AnalyticData(byte[] recBytes, int recByteLength)  
  89.       {  
  90.           if (recByteLength < 2) { return string.Empty; }  
  91.  
  92.           bool fin = (recBytes[0] & 0x80) == 0x80; // 1bit,1表示最後一幀    
  93.           if (!fin){  
  94.               return string.Empty;// 超過一幀暫不處理   
  95.           }  
  96.  
  97.           bool mask_flag = (recBytes[1] & 0x80) == 0x80; // 是否包含掩碼    
  98.           if (!mask_flag){  
  99.               return string.Empty;// 不包含掩碼的暫不處理  
  100.           }  
  101.  
  102.           int payload_len = recBytes[1] & 0x7F; // 數據長度    
  103.  
  104.           byte[] masks = new byte[4];  
  105.           byte[] payload_data;  
  106.  
  107.           if (payload_len == 126){  
  108.               Array.Copy(recBytes, 4, masks, 0, 4);  
  109.               payload_len = (UInt16)(recBytes[2] << 8 | recBytes[3]);  
  110.               payload_data = new byte[payload_len];  
  111.               Array.Copy(recBytes, 8, payload_data, 0, payload_len);  
  112.  
  113.           }else if (payload_len == 127){  
  114.               Array.Copy(recBytes, 10, masks, 0, 4);  
  115.               byte[] uInt64Bytes = new byte[8];  
  116.               for (int i = 0; i < 8; i++){  
  117.                   uInt64Bytes[i] = recBytes[9 - i];  
  118.               }  
  119.               UInt64 len = BitConverter.ToUInt64(uInt64Bytes, 0);  
  120.  
  121.               payload_data = new byte[len];  
  122.               for (UInt64 i = 0; i < len; i++){  
  123.                   payload_data[i] = recBytes[i + 14];  
  124.               }  
  125.           }else{  
  126.               Array.Copy(recBytes, 2, masks, 0, 4);  
  127.               payload_data = new byte[payload_len];  
  128.               Array.Copy(recBytes, 6, payload_data, 0, payload_len);  
  129.  
  130.           }  
  131.  
  132.           for (var i = 0; i < payload_len; i++){  
  133.               payload_data[i] = (byte)(payload_data[i] ^ masks[i % 4]);  
  134.           }  
  135.             
  136.           return Encoding.UTF8.GetString(payload_data);  
  137.       }  
  138.  
  139.  
  140.       /// <summary>  
  141.       /// 打包服務器數據  
  142.       /// </summary>  
  143.       /// <param name="message">數據</param>  
  144.       /// <returns>數據包</returns>  
  145.       private static byte[] PackData(string message)  
  146.       {  
  147.           byte[] contentBytes = null;  
  148.           byte[] temp = Encoding.UTF8.GetBytes(message);  
  149.  
  150.           if (temp.Length < 126){  
  151.               contentBytes = new byte[temp.Length + 2];  
  152.               contentBytes[0] = 0x81;  
  153.               contentBytes[1] = (byte)temp.Length;  
  154.               Array.Copy(temp, 0, contentBytes, 2, temp.Length);  
  155.           }else if (temp.Length < 0xFFFF){  
  156.               contentBytes = new byte[temp.Length + 4];  
  157.               contentBytes[0] = 0x81;  
  158.               contentBytes[1] = 126;  
  159.               contentBytes[2] = (byte)(temp.Length & 0xFF);  
  160.               contentBytes[3] = (byte)(temp.Length >> 8 & 0xFF);  
  161.               Array.Copy(temp, 0, contentBytes, 4, temp.Length);  
  162.           }else{  
  163.               // 暫不處理超長內容    
  164.           }  
  165.  
  166.           return contentBytes;  
  167.       }    
  168.   } 

或者參考這裏

ok! 基本上能實現傳輸文字了,接下來是圖像 可以通過base64編碼的方式傳輸 也可以通過二進制傳輸


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章