I started creating a tcp server that can receive many clients and simultaneously receive new data from all clients.
So far, I have used IOCP for tcp servers, which were quite lightweight and convenient, but this time I want to use Async / Await technology. which was released in C # 5.0.
The problem is that when I started writing the server using async / await, I realized that when using the tcp server for several async / await tech users. and conventional synchronization methods will work the same.
Here is a simple example:
class Server { private TcpListener _tcpListener; private List<TcpClient> _clients; private bool IsStarted; public Server(int port) { _tcpListener = new TcpListener(new IPEndPoint(IPAddress.Any, port)); _clients = new List<TcpClient>(); IsStarted = false; } public void Start() { IsStarted = true; _tcpListener.Start(); Task.Run(() => StartAcceptClientsAsync()); } public void Stop() { IsStarted = false; _tcpListener.Stop(); } private async Task StartAcceptClientsAsync() { while (IsStarted) {
Now, if you see the lines under "Note 1" and "Note 2", it can easily be changed to:
Note 1 of
var acceptedClient = await _tcpListener.AcceptTcpClientAsync();
to
var acceptedClient = _tcpListener.AcceptTcpClient();
And note 2 of
int packetSize = await acceptedClient.GetStream().ReadAsync(buffer, 0, 1024);
to
int packetSize = acceptedClient.GetStream().Read(buffer, 0, 1024);
And the server will work exactly the same.
So why use async / await in a tcp listener for multiple users if it is the same as using regular synchronization methods?
Should I continue to use IOCP in this case? , because for me it is quite easy and convenient, but I'm afraid that it will become obsolete or even no longer available in new versions of .NET.