HTML 5 WebSocket实现实时视频文字传输(2)
			
	客户端
	在支持WebSocket的浏览器中,可以直接在Javascript中通过WebSocket对象来实现通信。WebSocket对象主要通过onopen,onmessage,onclose即onerror四个事件实现对socket消息的异步响应。
	请创建静态页面 不用创建ruant=“server”的 否则会自动reload
	
		
			
			
			
				
					
						
							| 
								03
							 | 
							
								<html xmlns="http://www.w3.org/1999/xhtml">
							 | 
						
					
				
			 
			
			
			
				
					
						
							| 
								06
							 | 
							
								    <script type="text/javascript">
							 | 
						
					
				
			 
			
				
					
						
							| 
								07
							 | 
							
								        var wsServer = 'ws://localhost:9999/webSocket.ashx'; //基于.NET4.5服务器地址 
							 | 
						
					
				
			 
			
				
					
						
							| 
								08
							 | 
							
								        //var wsServer = 'ws://localhost:1818'; //基于.NET服务器地址 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								10
							 | 
							
								        var websocket = new WebSocket(wsServer); //创建WebSocket对象 
							 | 
						
					
				
			 
			
				
					
						
							| 
								11
							 | 
							
								        //websocket.send("hello");//向服务器发送消息 
							 | 
						
					
				
			 
			
				
					
						
							| 
								12
							 | 
							
								        //alert(websocket.readyState);//查看websocket当前状态 
							 | 
						
					
				
			 
			
				
					
						
							| 
								13
							 | 
							
								        websocket.onopen = function (evt) { 
							 | 
						
					
				
			 
			
			
			
			
				
					
						
							| 
								17
							 | 
							
								        websocket.onclose = function (evt) { 
							 | 
						
					
				
			 
			
			
			
			
				
					
						
							| 
								21
							 | 
							
								        websocket.onmessage = function (evt) { 
							 | 
						
					
				
			 
			
				
					
						
							| 
								22
							 | 
							
								            //收到服务器消息,使用evt.data提取 
							 | 
						
					
				
			 
			
			
			
			
				
					
						
							| 
								26
							 | 
							
								            writeToScreen(evt.data); 
							 | 
						
					
				
			 
			
			
			
				
					
						
							| 
								29
							 | 
							
								        websocket.onerror = function (evt) { 
							 | 
						
					
				
			 
			
			
			
				
					
						
							| 
								32
							 | 
							
								            writeToScreen(evt.message); 
							 | 
						
					
				
			 
			
			
			
				
					
						
							| 
								35
							 | 
							
								            if (websocket.readyState == websocket.OPEN) { 
							 | 
						
					
				
			 
			
				
					
						
							| 
								36
							 | 
							
								                msg = document.getElementById("msg").value; 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								38
							 | 
							
								                writeToScreen("发送成功!"); 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								40
							 | 
							
								                writeToScreen("连接失败!"); 
							 | 
						
					
				
			 
			
			
			
			
				
					
						
							| 
								44
							 | 
							
								        function writeToScreen(message) { 
							 | 
						
					
				
			 
			
				
					
						
							| 
								45
							 | 
							
								            var pre = document.createElement("p"); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								46
							 | 
							
								            pre.style.wordWrap = "break-word"; 
							 | 
						
					
				
			 
			
				
					
						
							| 
								47
							 | 
							
								            pre.innerHTML += message; 
							 | 
						
					
				
			 
			
				
					
						
							| 
								48
							 | 
							
								            output.appendChild(pre); 
							 | 
						
					
				
			 
			
			
			
			
			
			
				
					
						
							| 
								54
							 | 
							
								        <input type="text" id="msg" value="beyond is number one!" />
							 | 
						
					
				
			 
			
				
					
						
							| 
								55
							 | 
							
								        <button onclick="sendMsg()">send</button>
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								57
							 | 
							
								    <div id="output"></div>
							 | 
						
					
				
			 
			
			
		 
	 
 
	
	readyState表示连接有四种状态:
	CONNECTING (0):表示还没建立连接;
	OPEN (1): 已经建立连接,可以进行通讯;
	CLOSING (2):通过关闭握手,正在关闭连接;
	CLOSED (3):连接已经关闭或无法打开;
	url是代表 WebSocket 服务器的网络地址,协议通常是”ws”或“wss(加密通信)”,send 方法就是发送数据到服务器端;
	close 方法就是关闭连接;
	onopen连接建立,即握手成功触发的事件;
	onmessage收到服务器消息时触发的事件;
	onerror异常触发的事件;
	onclose关闭连接触发的事件;
	先说说基于.NET4.5的吧 ashx里面应该是这样写的
	
		
			
			
				
					
						
							| 
								02
							 | 
							
								            HttpContext.Current.AcceptWebSocketRequest(async (context) => 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								04
							 | 
							
								                WebSocket socket = context.WebSocket;//Socket 
							 | 
						
					
				
			 
			
			
			
				
					
						
							| 
								07
							 | 
							
								                    ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								08
							 | 
							
								                    CancellationToken token; 
							 | 
						
					
				
			 
			
				
					
						
							| 
								09
							 | 
							
								                    WebSocketReceiveResult result = 
							 | 
						
					
				
			 
			
				
					
						
							| 
								10
							 | 
							
								                            await socket.ReceiveAsync(buffer, token); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								11
							 | 
							
								                    if (socket.State == WebSocketState.Open) 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								13
							 | 
							
								                        string userMessage = Encoding.UTF8.GetString(buffer.Array, 0, 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								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); 
							 | 
						
					
				
			 
			
			
			
			
		 
	 
 
	
	然后需要注意的是 部署到IIS8上面  转到 Windows程序和功能 -打开Windows功能里面 IIS选项启动4.5 和WebSocket支持  否则会报错误的。
	如果你不是Windows8 或者IIS的问题 你可以使用其他方式实现websocket服务器 比如.net socket模拟(因为websocket本身就是基于TCP的完全可以模拟只是规则特别..)
	网上有人写了下面一段
	
		
			
			
			
				
					
						
							| 
								003
							 | 
							
								      static void Main(string[] args) 
							 | 
						
					
				
			 
			
			
			
				
					
						
							| 
								006
							 | 
							
								          byte[] buffer = new byte[1024]; 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								008
							 | 
							
								          IPEndPoint localEP = new IPEndPoint(IPAddress.Any, port); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								009
							 | 
							
								          Socket listener = new Socket(localEP.Address.AddressFamily,SocketType.Stream, ProtocolType.Tcp); 
							 | 
						
					
				
			 
			
			
			
				
					
						
							| 
								012
							 | 
							
								              listener.Bind(localEP); 
							 | 
						
					
				
			 
			
			
			
				
					
						
							| 
								015
							 | 
							
								              Console.WriteLine("等待客户端连接...."); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								016
							 | 
							
								              Socket sc = listener.Accept();//接受一个连接 
							 | 
						
					
				
			 
			
				
					
						
							| 
								017
							 | 
							
								              Console.WriteLine("接受到了客户端:"+sc.RemoteEndPoint.ToString()+"连接...."); 
							 | 
						
					
				
			 
			
			
			
				
					
						
							| 
								020
							 | 
							
								              int length = sc.Receive(buffer);//接受客户端握手信息 
							 | 
						
					
				
			 
			
				
					
						
							| 
								021
							 | 
							
								              sc.Send(PackHandShakeData(GetSecKeyAccetp(buffer,length))); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								022
							 | 
							
								              Console.WriteLine("已经发送握手协议了...."); 
							 | 
						
					
				
			 
			
			
			
				
					
						
							| 
								025
							 | 
							
								              Console.WriteLine("等待客户端数据...."); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								026
							 | 
							
								              length = sc.Receive(buffer);//接受客户端信息 
							 | 
						
					
				
			 
			
				
					
						
							| 
								027
							 | 
							
								              string clientMsg=AnalyticData(buffer, length); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								028
							 | 
							
								              Console.WriteLine("接受到客户端数据:" + clientMsg); 
							 | 
						
					
				
			 
			
			
			
				
					
						
							| 
								031
							 | 
							
								              string sendMsg = "您好," + clientMsg; 
							 | 
						
					
				
			 
			
				
					
						
							| 
								032
							 | 
							
								              Console.WriteLine("发送数据:“"+sendMsg+"” 至客户端...."); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								033
							 | 
							
								              sc.Send(PackData(sendMsg)); 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								035
							 | 
							
								              Console.WriteLine("演示Over!"); 
							 | 
						
					
				
			 
			
			
			
			
			
				
					
						
							| 
								040
							 | 
							
								              Console.WriteLine(e.ToString()); 
							 | 
						
					
				
			 
			
			
			
			
			
			
			
			
				
					
						
							| 
								048
							 | 
							
								      /// Sec-WebSocket-Accept 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								050
							 | 
							
								      private static byte[] PackHandShakeData(string secKeyAccept) 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								052
							 | 
							
								          var responseBuilder = new StringBuilder(); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								053
							 | 
							
								          responseBuilder.Append("HTTP/1.1 101 Switching Protocols" + Environment.NewLine); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								054
							 | 
							
								          responseBuilder.Append("Upgrade: websocket" + Environment.NewLine); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								055
							 | 
							
								          responseBuilder.Append("Connection: Upgrade" + Environment.NewLine); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								056
							 | 
							
								          responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine + Environment.NewLine); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								057
							 | 
							
								          //如果把上一行换成下面两行,才是thewebsocketprotocol-17协议,但居然握手不成功,目前仍没弄明白! 
							 | 
						
					
				
			 
			
				
					
						
							| 
								058
							 | 
							
								          //responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								059
							 | 
							
								          //responseBuilder.Append("Sec-WebSocket-Protocol: chat" + Environment.NewLine); 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								061
							 | 
							
								          return Encoding.UTF8.GetBytes(responseBuilder.ToString()); 
							 | 
						
					
				
			 
			
			
			
			
			
				
					
						
							| 
								066
							 | 
							
								      /// 生成Sec-WebSocket-Accept 
							 | 
						
					
				
			 
			
			
			
				
					
						
							| 
								069
							 | 
							
								      /// Sec-WebSocket-Accept 
							 | 
						
					
				
			 
			
				
					
						
							| 
								070
							 | 
							
								      private static string GetSecKeyAccetp(byte[] handShakeBytes,int bytesLength) 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								072
							 | 
							
								          string handShakeText = Encoding.UTF8.GetString(handShakeBytes, 0, bytesLength); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								073
							 | 
							
								          string key = string.Empty; 
							 | 
						
					
				
			 
			
				
					
						
							| 
								074
							 | 
							
								          Regex r = new Regex(@"Sec\-WebSocket\-Key:(.*?)\r\n"); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								075
							 | 
							
								          Match m = r.Match(handShakeText); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								076
							 | 
							
								          if (m.Groups.Count != 0) 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								078
							 | 
							
								              key = Regex.Replace(m.Value, @"Sec\-WebSocket\-Key:(.*?)\r\n", "$1").Trim(); 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								080
							 | 
							
								          byte[] encryptionString = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(key +"258EAFA5-E914-47DA-95CA-C5AB0DC85B11")); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								081
							 | 
							
								          return Convert.ToBase64String(encryptionString); 
							 | 
						
					
				
			 
			
			
			
			
			
			
			
			
			
			
				
					
						
							| 
								091
							 | 
							
								      private static string AnalyticData(byte[] recBytes, int recByteLength) 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								093
							 | 
							
								          if (recByteLength < 2) { return string.Empty; } 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								095
							 | 
							
								          bool fin = (recBytes[0] & 0x80) == 0x80; // 1bit,1表示最后一帧   
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								097
							 | 
							
								              return string.Empty;// 超过一帧暂不处理  
							 | 
						
					
				
			 
			
			
			
				
					
						
							| 
								100
							 | 
							
								          bool mask_flag = (recBytes[1] & 0x80) == 0x80; // 是否包含掩码   
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								102
							 | 
							
								              return string.Empty;// 不包含掩码的暂不处理 
							 | 
						
					
				
			 
			
			
			
				
					
						
							| 
								105
							 | 
							
								          int payload_len = recBytes[1] & 0x7F; // 数据长度   
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								107
							 | 
							
								          byte[] masks = new byte[4]; 
							 | 
						
					
				
			 
			
			
			
				
					
						
							| 
								110
							 | 
							
								          if (payload_len == 126){ 
							 | 
						
					
				
			 
			
				
					
						
							| 
								111
							 | 
							
								              Array.Copy(recBytes, 4, masks, 0, 4); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								112
							 | 
							
								              payload_len = (UInt16)(recBytes[2] << 8 | recBytes[3]); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								113
							 | 
							
								              payload_data = new byte[payload_len]; 
							 | 
						
					
				
			 
			
				
					
						
							| 
								114
							 | 
							
								              Array.Copy(recBytes, 8, payload_data, 0, payload_len); 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								116
							 | 
							
								          }else if (payload_len == 127){ 
							 | 
						
					
				
			 
			
				
					
						
							| 
								117
							 | 
							
								              Array.Copy(recBytes, 10, masks, 0, 4); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								118
							 | 
							
								              byte[] uInt64Bytes = new byte[8]; 
							 | 
						
					
				
			 
			
				
					
						
							| 
								119
							 | 
							
								              for (int i = 0; i < 8; i++){ 
							 | 
						
					
				
			 
			
				
					
						
							| 
								120
							 | 
							
								                  uInt64Bytes[i] = recBytes[9 - i]; 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								122
							 | 
							
								              UInt64 len = BitConverter.ToUInt64(uInt64Bytes, 0); 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								124
							 | 
							
								              payload_data = new byte[len]; 
							 | 
						
					
				
			 
			
				
					
						
							| 
								125
							 | 
							
								              for (UInt64 i = 0; i < len; i++){ 
							 | 
						
					
				
			 
			
				
					
						
							| 
								126
							 | 
							
								                  payload_data[i] = recBytes[i + 14]; 
							 | 
						
					
				
			 
			
			
			
				
					
						
							| 
								129
							 | 
							
								              Array.Copy(recBytes, 2, masks, 0, 4); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								130
							 | 
							
								              payload_data = new byte[payload_len]; 
							 | 
						
					
				
			 
			
				
					
						
							| 
								131
							 | 
							
								              Array.Copy(recBytes, 6, payload_data, 0, payload_len); 
							 | 
						
					
				
			 
			
			
			
			
				
					
						
							| 
								135
							 | 
							
								          for (var i = 0; i < payload_len; i++){ 
							 | 
						
					
				
			 
			
				
					
						
							| 
								136
							 | 
							
								              payload_data[i] = (byte)(payload_data[i] ^ masks[i % 4]); 
							 | 
						
					
				
			 
			
			
			
				
					
						
							| 
								139
							 | 
							
								          return Encoding.UTF8.GetString(payload_data); 
							 | 
						
					
				
			 
			
			
			
			
			
			
			
			
			
			
				
					
						
							| 
								149
							 | 
							
								      private static byte[] PackData(string message) 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								151
							 | 
							
								          byte[] contentBytes = null; 
							 | 
						
					
				
			 
			
				
					
						
							| 
								152
							 | 
							
								          byte[] temp = Encoding.UTF8.GetBytes(message); 
							 | 
						
					
				
			 
			
			
				
					
						
							| 
								154
							 | 
							
								          if (temp.Length < 126){ 
							 | 
						
					
				
			 
			
				
					
						
							| 
								155
							 | 
							
								              contentBytes = new byte[temp.Length + 2]; 
							 | 
						
					
				
			 
			
				
					
						
							| 
								156
							 | 
							
								              contentBytes[0] = 0x81; 
							 | 
						
					
				
			 
			
				
					
						
							| 
								157
							 | 
							
								              contentBytes[1] = (byte)temp.Length; 
							 | 
						
					
				
			 
			
				
					
						
							| 
								158
							 | 
							
								              Array.Copy(temp, 0, contentBytes, 2, temp.Length); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								159
							 | 
							
								          }else if (temp.Length < 0xFFFF){ 
							 | 
						
					
				
			 
			
				
					
						
							| 
								160
							 | 
							
								              contentBytes = new byte[temp.Length + 4]; 
							 | 
						
					
				
			 
			
				
					
						
							| 
								161
							 | 
							
								              contentBytes[0] = 0x81; 
							 | 
						
					
				
			 
			
				
					
						
							| 
								162
							 | 
							
								              contentBytes[1] = 126; 
							 | 
						
					
				
			 
			
				
					
						
							| 
								163
							 | 
							
								              contentBytes[2] = (byte)(temp.Length & 0xFF); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								164
							 | 
							
								              contentBytes[3] = (byte)(temp.Length >> 8 & 0xFF); 
							 | 
						
					
				
			 
			
				
					
						
							| 
								165
							 | 
							
								              Array.Copy(temp, 0, contentBytes, 4, temp.Length); 
							 | 
						
					
				
			 
			
			
			
			
			
			
			
		 
	 
 
	
	或者参考这里 
	ok! 基本上能实现传输文字了,接下来是图像 可以通过base64编码的方式传输 也可以通过二进制传输