Last active
August 19, 2023 22:17
-
-
Save Maxwe11/cf8cc6331ad73671846e to your computer and use it in GitHub Desktop.
Async TcpListener/TcpClient example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Net; | |
using System.Net.Sockets; | |
using System.IO; | |
using System.Threading.Tasks; | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
MainAsync().GetAwaiter().GetResult(); | |
} | |
static async Task MainAsync() | |
{ | |
Console.WriteLine("Starting..."); | |
var server = new TcpListener(IPAddress.Parse("0.0.0.0"), 66); | |
server.Start(); | |
Console.WriteLine("Started."); | |
while (true) | |
{ | |
var client = await server.AcceptTcpClientAsync().ConfigureAwait(false); | |
var cw = new ClientWorking(client, true); | |
Task.Run((Func<Task>)cw.DoSomethingWithClientAsync); | |
} | |
} | |
} | |
class ClientWorking | |
{ | |
TcpClient _client; | |
bool _ownsClient; | |
public ClientWorking(TcpClient client, bool ownsClient) | |
{ | |
_client = client; | |
_ownsClient = ownsClient; | |
} | |
public async Task DoSomethingWithClientAsync() | |
{ | |
try | |
{ | |
using (var stream = _client.GetStream()) | |
{ | |
using (var sr = new StreamReader(stream)) | |
using (var sw = new StreamWriter(stream)) | |
{ | |
await sw.WriteLineAsync("Hi. This is x2 TCP/IP easy-to-use server").ConfigureAwait(false); | |
await sw.FlushAsync().ConfigureAwait(false); | |
var data = default(string); | |
while (!((data = await sr.ReadLineAsync().ConfigureAwait(false)).Equals("exit", StringComparison.OrdinalIgnoreCase))) | |
{ | |
await sw.WriteLineAsync(data).ConfigureAwait(false); | |
await sw.FlushAsync().ConfigureAwait(false); | |
} | |
} | |
} | |
} | |
finally | |
{ | |
if (_ownsClient && _client != null) | |
{ | |
(_client as IDisposable).Dispose(); | |
_client = null; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment