How to create a web socket client in C#?
I have a server in php and a WebSocket client in js in the browser. How to create a connection socket with the same server in C# via the tcp protocol? I use the standard library System. Net. WebSockets.
1 answers
I never used sockets, I decided to figure it out and this is what I got in the end:
As a server for sending, I will take Echo server websocket.org.
-
And so, the main client class for web sockets is
ClientWebSocket
, we have itIDisposable
, which means we useusing
:using var ws = new ClientWebSocket();
I use c# 8, so I have using in one line.
-
Then we look at what methods this object has and notice that in fact there are there are 3 main methods in total (
ConnectAsync()
,SendAsync()
andReceiveAsync()
. Let's now go in order:-
ConnectAsync()
- Connecting to the specified server, the input accepts two parameters (Uri
andCancellationToken
).await ws.ConnectAsync(new Uri("wss://echo.websocket.org"), CancellationToken.None);
-
SendAsync()
- Sends an array of bytes to the server indicating the type of the sent message. AcceptsArraySegment<byte>
,WebSocketMessageType
,bool
andCancellationToken
:ArraySegment<byte> arraySegment = new ArraySegment<byte>(Encoding.UTF8.GetBytes("Привет мир!")); await ws.SendAsync(arraySegment, System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None);
-
ReceiveAsync()
- Receives a response from the server. AcceptsArraySegment<byte>
as a buffer for writing data, andCancellationToken
.ArraySegment<byte> bytesReceived = new ArraySegment<byte>(new byte[1024]); WebSocketReceiveResult result = await ws.ReceiveAsync(bytesReceived, CancellationToken.None); var response = Encoding.UTF8.GetString(bytesReceived.Array, 0, result.Count);
-
That's actually all that is needed for the simplest work with web sockets in C#.
From the comments:
CancellationToken
- I used a stub everywhere, for example, it will do, but in the project it is better to create an objectCancellationTokenSource
, take a token from it and work with it. Otherwise, you are unlikely to complete the task correctly.-
ReceiveAsync()
- before receiving the data, you should probably check whether there is a connection at all. This is done approximately so:if (ws.State == WebSocketState.Open) { //Мы подключились и можем отправлять данные. }
On the Internet, I saw what they do
while
cycle, which turns to infinity, until the statusOpen
, then see for yourself how you need it.