客戶端
在支持WebSocket的瀏覽器中,可以直接在Javascript中通過WebSocket對象來實現通信。WebSocket對象主要通過onopen,onmessage,onclose即onerror四個事件實現對socket消息的異步響應。
請創建靜態頁面 不用創建ruant=“server”的 否則會自動reload
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title></title>
- <script type="text/javascript">
- var wsServer = 'ws://localhost:9999/webSocket.ashx'; //基於.NET4.5服務器地址
- //var wsServer = 'ws://localhost:1818'; //基於.NET服務器地址
- var websocket = new WebSocket(wsServer); //創建WebSocket對象
- //websocket.send("hello");//向服務器發送消息
- //alert(websocket.readyState);//查看websocket當前狀態
- websocket.onopen = function (evt) {
- //已經建立連接
- alert("已經建立連接");
- };
- websocket.onclose = function (evt) {
- //已經關閉連接
- alert("已經關閉連接");
- };
- websocket.onmessage = function (evt) {
- //收到服務器消息,使用evt.data提取
- evt.stopPropagation()
- evt.preventDefault()
- //alert(evt.data);
- writeToScreen(evt.data);
- //websocket.close();
- };
- websocket.onerror = function (evt) {
- //產生異常
- //alert(evt.message);
- writeToScreen(evt.message);
- };
- function sendMsg() {
- if (websocket.readyState == websocket.OPEN) {
- msg = document.getElementById("msg").value;
- websocket.send(msg);
- writeToScreen("發送成功!");
- } else {
- writeToScreen("連接失敗!");
- }
- }
- function writeToScreen(message) {
- var pre = document.createElement("p");
- pre.style.wordWrap = "break-word";
- pre.innerHTML += message;
- output.appendChild(pre);
- }
- </script>
- </head>
- <body>
- <div>
- <input type="text" id="msg" value="beyond is number one!" />
- <button onclick="sendMsg()">send</button>
- </div>
- <div id="output"></div>
- </body>
- </html>
readyState表示連接有四種狀態:
CONNECTING (0):表示還沒建立連接;
OPEN (1): 已經建立連接,可以進行通訊;
CLOSING (2):通過關閉握手,正在關閉連接;
CLOSED (3):連接已經關閉或無法打開;
url是代表 WebSocket 服務器的網絡地址,協議通常是”ws”或“wss(加密通信)”,send 方法就是發送數據到服務器端;
close 方法就是關閉連接;
onopen連接建立,即握手成功觸發的事件;
onmessage收到服務器消息時觸發的事件;
onerror異常觸發的事件;
onclose關閉連接觸發的事件;
先說說基於.NET4.5的吧 ashx裏面應該是這樣寫的
- //得到當前WebSocket請求
- HttpContext.Current.AcceptWebSocketRequest(async (context) =>
- {
- WebSocket socket = context.WebSocket;//Socket
- while (true)
- {
- ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
- CancellationToken token;
- WebSocketReceiveResult result =
- await socket.ReceiveAsync(buffer, token);
- if (socket.State == WebSocketState.Open)
- {
- string userMessage = Encoding.UTF8.GetString(buffer.Array, 0,
- result.Count);
- userMessage = "You sent: " + userMessage + " at " +
- DateTime.Now.ToLongTimeString();
- buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMessage));
- await socket.SendAsync(buffer, WebSocketMessageType.Text,
- true, CancellationToken.None);
- }
- else { break; }
- }
- });
然後需要注意的是 部署到IIS8上面 轉到 Windows程序和功能 -打開Windows功能裏面 IIS選項啓動4.5 和WebSocket支持 否則會報錯誤的。
如果你不是Windows8 或者IIS的問題 你可以使用其他方式實現websocket服務器 比如.net socket模擬(因爲websocket本身就是基於TCP的完全可以模擬只是規則特別..)
網上有人寫了下面一段
- class Program
- {
- static void Main(string[] args)
- {
- int port = 1818;
- byte[] buffer = new byte[1024];
- IPEndPoint localEP = new IPEndPoint(IPAddress.Any, port);
- Socket listener = new Socket(localEP.Address.AddressFamily,SocketType.Stream, ProtocolType.Tcp);
- try{
- listener.Bind(localEP);
- listener.Listen(10);
- Console.WriteLine("等待客戶端連接....");
- Socket sc = listener.Accept();//接受一個連接
- Console.WriteLine("接受到了客戶端:"+sc.RemoteEndPoint.ToString()+"連接....");
- //握手
- int length = sc.Receive(buffer);//接受客戶端握手信息
- sc.Send(PackHandShakeData(GetSecKeyAccetp(buffer,length)));
- Console.WriteLine("已經發送握手協議了....");
- //接受客戶端數據
- Console.WriteLine("等待客戶端數據....");
- length = sc.Receive(buffer);//接受客戶端信息
- string clientMsg=AnalyticData(buffer, length);
- Console.WriteLine("接受到客戶端數據:" + clientMsg);
- //發送數據
- string sendMsg = "您好," + clientMsg;
- Console.WriteLine("發送數據:“"+sendMsg+"” 至客戶端....");
- sc.Send(PackData(sendMsg));
- Console.WriteLine("演示Over!");
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- }
- /// <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;
- }
- }
或者參考這裏
ok! 基本上能實現傳輸文字了,接下來是圖像 可以通過base64編碼的方式傳輸 也可以通過二進制傳輸