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


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

最近在研究視頻傳輸給瀏覽器,然后使用H5標簽解碼。視頻流采用websocket傳輸。所以研究了一下C#的websocket。

首先使用HttpListener進行偵聽,HttpListener監聽需要啟動管理員權限才能運行,或者注冊該端口,注冊如下:

已管理員身份運行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=dell

 

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

第一步:創建HttpListener類,並啟動監聽:

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

第二步:等待連接

            var context = listener.GetContext();

第三步:接收websocket

            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.


 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM