I'm creating an asynchronous server that can have multiple clients. Similar to a chat client/server architecture, all clients are updated on each server state change based on any client's request. I've found a lot of examples to follow and wrote a simple application for testing. I've just written the processing of client requests for now but have come across a situation that I normally don't encounter. Here's the sample server I wrote:
class Server
{
int _port;
TcpListener _listener;
IList<TcpClient> _clients = new List<TcpClient>();
public Server(int port)
{
_port = port;
_listener = new TcpListener(IPAddress.Any, _port);
}
public async Task StartListening()
{
_listener.Start();
Console.WriteLine("The server is listening on port {0}...", _port);
while (true)
{
try
{
var client = await _listener.AcceptTcpClientAsync();
Console.WriteLine("We have a client!");
_clients.Add(client);
Process(client);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
private async Task Process(TcpClient client)
{
try
{
var stream = client.GetStream();
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream) { AutoFlush = true };
char[] buffer = new char[1024];
while (true)
{
var request = await reader.ReadLineAsync();
if (request != null)
{
Console.WriteLine(request);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
client.Close();
}
}
}
Here's Program.cs:
class Program
{
static void Main(string[] args)
{
var server = new Server(6029);
server.StartListening().Wait();
}
}
I get a warning on the Process call since the Task isn't awaited. I understand the behavior of the code without the await call but I'm wondering if I should be coding this differently (ThreadPool, etc...) even though this gives me the behavior that I want. Should Tasks always be awaited?