Skip to content

Commit 35cc5e8

Browse files
authored
Create 2.md
1 parent 6c1612f commit 35cc5e8

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

2.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
```

0 commit comments

Comments
 (0)