基於C#net4.5websocket客戶端與服務端

只支持win8以上系統以及windows server2012以上系統html

最近在研究視頻傳輸給瀏覽器,而後使用H5標籤解碼。視頻流採用websocket傳輸。因此研究了一下C#的websocket。web

首先使用HttpListener進行偵聽,HttpListener監聽須要啓動管理員權限才能運行,或者註冊該端口,註冊以下:windows

已管理員身份運行cmd.exe 輸入下面兩個命令
netsh http delete urlacl url=http://127.0.0.1:8080/ 瀏覽器

netsh http add urlacl url=http://127.0.0.1:8080/  user=dellwebsocket

 

*******************websocket服務端****************************************app

第一步:建立HttpListener類,並啓動監聽:異步

            var listener = new HttpListener();
            listener.Prefixes.Add("http://10.10.13.140:8080/");
            listener.Start();

第二步:等待鏈接socket

            var context = listener.GetContext();

第三步:接收websocketpost

            var wsContext = await context.AcceptWebSocketAsync(null);
            var ws = wsContext.WebSocket;
            Console.WriteLine("WebSocket connect");

 

第四步:開始異步接收數據學習

                    //接收數據
                    var wsdata = await ws.ReceiveAsync(abuf, cancel);
                    Console.WriteLine(wsdata.Count);
                    byte[] bRec = new byte[wsdata.Count];
                    Array.Copy(buf, bRec, wsdata.Count);
                    Console.WriteLine(Encoding.Default.GetString(bRec));

 

第五步:釋放資源

1  //注意,使用完,記得釋放,否則會有內存泄漏
2 ws.Dispose();

 

*******************websocket客戶端****************************************

這裏使用ClientWebSocket類進行

第一步:建立ClientWebSocket

ClientWebSocket webSocket = new ClientWebSocket();
 

第二步:創建websocket鏈接

await webSocket.ConnectAsync(new Uri("ws://10.10.13.140:8080/"), cancellation);
 
Console.WriteLine(111);

第三步:發送數據

1 //發送數據
2  
3 await webSocket.SendAsync(new ArraySegment<byte>(bsend), WebSocketMessageType.Binary, true, cancellation);
4  
5  await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "1", cancellation);

 

第四步:釋放資源
 
//釋放資源
 
webSocket.Dispose();

 

爲了方便你們學習,整理了一下服務端和客戶端的代碼,採用C# net4.5 vs2017開發環境

鏈接以下:

點擊打開連接

*************--------------備註---------------******************************************

 

發現win7下沒法運行,參考

https://msdn.microsoft.com/en-us/library/system.net.websockets.clientwebsocket(v=vs.110).aspx

關鍵部分以下:

Some of the classes and class elements in the System.Net.WebSockets namespace are supported on Windows 7, Windows Vista SP2, and Windows Server 2008. However, the only public implementations of client and server WebSockets are supported on Windows 8 and Windows Server 2012. The class elements in the System.Net.WebSockets namespace that are supported on Windows 7, Windows Vista SP2, and Windows Server 2008 are abstract class elements. This allows an application developer to inherit and extend these abstract class classes and class elements with an actual implementation of client WebSockets.

相關文章
相關標籤/搜索