@@ -5,41 +5,58 @@ Below is a modern asynchronous server using modern .NET APIs:
5
5
- Range syntax for slicing the buffer
6
6
7
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 ));
8
+ using var listenSocket = new Socket (SocketType .Stream , ProtocolType .Tcp );
9
+ listenSocket .Bind (new IPEndPoint (IPAddress .Loopback , 8080 ));
12
10
13
- Console .WriteLine ($" Listening on {listenSocket .LocalEndPoint }" );
11
+ Console .WriteLine ($" Listening on {listenSocket .LocalEndPoint }" );
14
12
15
- listenSocket .Listen ();
13
+ listenSocket .Listen ();
16
14
17
- while (true )
18
- {
19
- // Wait for a new connection to arrive
20
- var connection = await listenSocket .AcceptAsync ();
15
+ while (true )
16
+ {
17
+ // Wait for a new connection to arrive
18
+ var connection = await listenSocket .AcceptAsync ();
21
19
22
- // We got a new connection spawn a task to so that we can echo the contents of the connection
23
- _ = Task .Run (async () =>
20
+ // We got a new connection spawn a task to so that we can echo the contents of the connection
21
+ _ = Task .Run (async () =>
22
+ {
23
+ var buffer = new byte [4096 ];
24
+ try
24
25
{
25
- var buffer = new byte [4096 ];
26
- try
26
+ while (true )
27
27
{
28
- while (true )
28
+ int read = await connection .ReceiveAsync (buffer , SocketFlags .None );
29
+ if (read == 0 )
29
30
{
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 );
31
+ break ;
36
32
}
33
+ await connection .SendAsync (buffer [.. read ], SocketFlags .None );
37
34
}
38
- finally
39
- {
40
- connection . Dispose ();
41
- }
42
- });
43
- }
35
+ }
36
+ finally
37
+ {
38
+ connection . Dispose ();
39
+ }
40
+ });
44
41
}
45
42
```
43
+
44
+ ## Asynchronous Socket Client
45
+
46
+ Below is a modern asynchronous server using modern .NET APIs:
47
+ - Uses Task based APIs to establish the connection.
48
+ - Creates a ` NetworkStream ` over the ` Socket ` in order to use ` CopyToAsync ` , a helper that makes it easy to copy content from one ` Stream ` to another.
49
+
50
+ ``` C#
51
+ using var socket = new Socket (SocketType .Stream , ProtocolType .Tcp );
52
+ await socket .ConnectAsync (new IPEndPoint (IPAddress .Loopback , 8080 ));
53
+
54
+ Console .WriteLine (" Type into the console to echo the contents" );
55
+
56
+ var ns = new NetworkStream (socket );
57
+ var readTask = Console .OpenStandardInput ().CopyToAsync (ns );
58
+ var writeTask = ns .CopyToAsync (Console .OpenStandardOutput ());
59
+
60
+ // Quit if any of the tasks complete
61
+ await Task .WhenAny (readTask , writeTask );
62
+ ```
0 commit comments