using System.Net; using System.Net.Sockets; using System.Threading.Tasks; public async Task WaitForClientAsync() { var listener = new TcpListener(IPAddress.Any, 1234); listener.Start(); // wait for a client to connect Socket socket = await listener.AcceptSocketAsync(); // process the connection // ... socket.Close(); listener.Stop(); }
using System.Net; using System.Net.Sockets; using System.Threading.Tasks; public async Task ListenForClientsAsync() { var listener = new TcpListener(IPAddress.Any, 1234); listener.Start(); while (true) { // wait for a client to connect Socket socket = await listener.AcceptSocketAsync(); // process the connection asynchronously Task.Run(() => ProcessConnectionAsync(socket)); } } private async Task ProcessConnectionAsync(Socket socket) { // ... socket.Close(); }This example shows how AcceptSocketAsync() can be used to listen for multiple clients simultaneously. The ListenForClientsAsync() method uses a while loop to continuously wait for clients to connect and then creates a new background task to process each connection asynchronously. Package library: System.Net.Sockets.