Skip to content

Commit c08118f

Browse files
authored
Update 2.md
1 parent 35cc5e8 commit c08118f

File tree

1 file changed

+44
-27
lines changed

1 file changed

+44
-27
lines changed

2.md

Lines changed: 44 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -5,41 +5,58 @@ Below is a modern asynchronous server using modern .NET APIs:
55
- Range syntax for slicing the buffer
66

77
```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));
1210

13-
Console.WriteLine($"Listening on {listenSocket.LocalEndPoint}");
11+
Console.WriteLine($"Listening on {listenSocket.LocalEndPoint}");
1412

15-
listenSocket.Listen();
13+
listenSocket.Listen();
1614

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();
2119

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
2425
{
25-
var buffer = new byte[4096];
26-
try
26+
while (true)
2727
{
28-
while (true)
28+
int read = await connection.ReceiveAsync(buffer, SocketFlags.None);
29+
if (read == 0)
2930
{
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;
3632
}
33+
await connection.SendAsync(buffer[..read], SocketFlags.None);
3734
}
38-
finally
39-
{
40-
connection.Dispose();
41-
}
42-
});
43-
}
35+
}
36+
finally
37+
{
38+
connection.Dispose();
39+
}
40+
});
4441
}
4542
```
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

Comments
 (0)