File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## Asynchronous Socket Server
2
+
3
+ Below is a modern asynchronous server using modern .NET APIs:
4
+ - Task based APIs for asynchronous accept/read/write
5
+ - Range syntax for slicing the buffer
6
+
7
+ ``` C#
8
+ public static async Task AsynchronousEchoServer ()
9
+ {
10
+ using var listenSocket = new Socket (SocketType .Stream , ProtocolType .Tcp );
11
+ listenSocket .Bind (new IPEndPoint (IPAddress .Loopback , 8080 ));
12
+
13
+ Console .WriteLine ($" Listening on {listenSocket .LocalEndPoint }" );
14
+
15
+ listenSocket .Listen ();
16
+
17
+ while (true )
18
+ {
19
+ // Wait for a new connection to arrive
20
+ var connection = await listenSocket .AcceptAsync ();
21
+
22
+ // We got a new connection spawn a task to so that we can echo the contents of the connection
23
+ _ = Task .Run (async () =>
24
+ {
25
+ var buffer = new byte [4096 ];
26
+ try
27
+ {
28
+ while (true )
29
+ {
30
+ int read = await connection .ReceiveAsync (buffer , SocketFlags .None );
31
+ if (read == 0 )
32
+ {
33
+ break ;
34
+ }
35
+ await connection .SendAsync (buffer [.. read ], SocketFlags .None );
36
+ }
37
+ }
38
+ finally
39
+ {
40
+ connection .Dispose ();
41
+ }
42
+ });
43
+ }
44
+ }
45
+ ```
You can’t perform that action at this time.
0 commit comments