無心中發現js有webSocket對象因而百度了一下客戶端代碼與服務端代碼沒有現成的javascript
有的就有一些簡單了鏈接例子有的還很差使 因而就本身整理了一下html
c#編寫的服務端代碼java
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; using System.Security.Cryptography; using System.Threading; using System.Collections; namespace WebSocket { public struct UserInfo { public string username; //用戶名 public Socket clientSocket; // public string IP; //用戶ip public string xb; } class Program { private static Socket listener; private static Hashtable ht; static void Main(string[] args) { int port = 1818;//監聽端口爲1818端口 ht = new Hashtable();//用於存放客戶端的鏈接socket byte[] buffer = new byte[1024]; IPEndPoint localEP = new IPEndPoint(IPAddress.Any, port); listener = new Socket(localEP.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { listener.Bind(localEP); listener.Listen(10); Console.WriteLine("等待客戶端鏈接...."); while (true) { Thread th = new Thread(Receive); th.Start(); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } /// <summary> /// 線程調用 /// </summary> private static void Receive() { Socket clientSocket = listener.Accept(); //接收到客戶端的鏈接 clientSocket.Blocking = true; IPEndPoint clientipe = (IPEndPoint)clientSocket.RemoteEndPoint; // Console.WriteLine("[" + clientipe.Address.ToString() + "] Connected"); if (!ht.ContainsKey(clientipe.Address.ToString())) { //將ip地址設置爲hashTable的key值 若hashTable中存在該ip地址則再也不ht中添加socket以避免發送重複數據 ht.Add(clientipe.Address.ToString(), clientSocket); } Console.WriteLine("接收到了客戶端:ip" + clientSocket.RemoteEndPoint.ToString() + "的鏈接"); byte[] buffer = new byte[1024]; int length = clientSocket.Receive(buffer); clientSocket.Send(PackHandShakeData(GetSecKeyAccetp(buffer, length))); Console.WriteLine("已經發送握手協議了...."); //接收用戶姓名信息 length = clientSocket.Receive(buffer); string xm = AnalyticData(buffer, length); while (true) { //接受客戶端數據 Console.WriteLine("等待客戶端數據...."); length = clientSocket.Receive(buffer);//接受客戶端信息 string clientMsg = AnalyticData(buffer, length); Console.WriteLine("接受到客戶端數據:" + clientMsg); //發送數據 string sendMsg = "" + clientMsg; Console.WriteLine("發送數據:「" + sendMsg + "」 至客戶端...."); //遍歷hashTable中的數據獲取Socket發送數據 foreach (DictionaryEntry de in ht) { Socket sc = (Socket)de.Value; sc.Send(PackData(clientSocket.RemoteEndPoint.ToString() +xm+ "說:" + sendMsg)); } Thread.Sleep(1000); //clientSocket.Send(PackData(sendMsg)); } } /// <summary> /// 打包握手信息 /// </summary> /// <param name="secKeyAccept">Sec-WebSocket-Accept</param> /// <returns>數據包</returns> private static byte[] PackHandShakeData(string secKeyAccept) { var responseBuilder = new StringBuilder(); responseBuilder.Append("HTTP/1.1 101 Switching Protocols" + Environment.NewLine); responseBuilder.Append("Upgrade: websocket" + Environment.NewLine); responseBuilder.Append("Connection: Upgrade" + Environment.NewLine); responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine + Environment.NewLine); //若是把上一行換成下面兩行,纔是thewebsocketprotocol-17協議,但竟然握手不成功,目前仍沒弄明白! //responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine); //responseBuilder.Append("Sec-WebSocket-Protocol: chat" + Environment.NewLine); return Encoding.UTF8.GetBytes(responseBuilder.ToString()); } /// <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); } /// <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; } } }
這個服務端代碼還有一個小問題剛運行一會會報web
不知是我電腦的問題仍是線程那塊的問題 有多是死循環那塊形成的 若是有知道的麻煩告訴一下c#
Html頁面代碼這個頁面是百度的。。。。服務器
<!DOCTYPE html> <html> <head> <title>Web Socket Client</title> </head> <body style="padding:10px;"> <h1>聊天室</h1> <div style="margin:5px 0px;"> Address: <div><input id="address" type="text" value="ws://127.0.0.1:1818" style="width:400px;"/></div> </div> <div style="margin:5px 0px;"> Name: <div><input id="name" type="text" value="Byron" style="width:400px;"/></div> </div> <div> <button id="connect" onclick="connect();">connect server</button> <button id="disconnect" onclick="quit();">disconnect</button> <button id="clear" onclick="clearMsg();">clear</button> </div> <h5 style="margin:4px 0px;">Message:</h5> <div id="message" style="border:solid 1px #333; padding:4px; width:400px; overflow:auto; background-color:#404040; height:300px; margin-bottom:8px; font-size:14px;"> </div> <input id="text" type="text" onkeypress="enter(event);" style="width:340px"/> <button id="send" onclick="send();">send</button> <script type="text/javascript"> var name=document.getElementById('name').value; var msgContainer=document.getElementById('message'); var text=document.getElementById('text'); function connect () { var address=document.getElementById('address').value; 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.onmessage=function(e){ var msg=document.createElement('div'); msg.style.color='#fff'; msg.innerHTML=e.data; msgContainer.appendChild(msg); }; ws.onerror=function(e){ var msg=document.createElement('div'); msg.style.color='#0f0'; msg.innerHTML='Server > '+e.data; msgContainer.appendChild(msg); }; ws.onclose=function(e){ var msg=document.createElement('div'); msg.style.color='#0f0'; msg.innerHTML="Server > connection closed by server."; msgContainer.appendChild(msg); }; text.focus(); } function quit(){ if(ws){ ws.close(); var msg=document.createElement('div'); msg.style.color='#0f0'; msg.innerHTML='Server > connection closed.'; msgContainer.appendChild(msg); ws=null; } } function send(){ ws.send(text.value); setTimeout(function(){ msgContainer.scrollTop=msgContainer.getBoundingClientRect().height; },100); text.value=''; text.focus(); } function clearMsg(){ msgContainer.innerHTML=""; } function enter(event){ if(event.keyCode==13){ send(); } } </script> </body> </html>
下面給你們截個圖websocket