Here is an async Tcp server using async/await I have written. I would be very appreciate if anyone can help to improve my code. Thank you!
public class TcpServer
{
private int DefaultPort = 6340;
public TcpListener TcpListener { get; set; }
public TcpServer()
{
var ip = NetworkHelper.GetLocalIPAddress();
var idAddress = IPAddress.Parse(ip as string);
TcpListener = new TcpListener(idAddress, DefaultPort );
ReceiveDataAsync();
}
private async void ReceiveDataAsync()
{
try
{
TcpListener.Start();
while (true)
{
var tcpClient = await TcpListener.AcceptTcpClientAsync();
ReadDataFromClientAsync(tcpClient);
}
}
catch (Exception e)
{
// To Log;
}
}
private async void ReadDataFromClientAsync(TcpClient client)
{
try
{
var stream = client.GetStream();
while (client.Connected)
{
List<byte> totalBytes = new List<byte>();
// The first 4 bytes record the length of the code.
var countBytes = new byte[4];
var count = await stream.ReadAsync(countBytes, 0, countBytes.Length);
// use this to detect if tcp client is connected.
if (count == 0)
{
break;
}
var size = BitConverter.ToInt32(countBytes, 0);
while (size > 0)
{
byte[] bytes;
if (size < 256)
{
bytes = new byte[size];
}
else
{
bytes = new byte[256];
}
var byteCount = await stream.ReadAsync(bytes, 0, bytes.Length);
totalBytes.AddRange(bytes);
size -= 256;
}
var message = Encoding.Default.GetString(totalBytes.ToArray(), 0, totalBytes.Count);
// Do some logic using the message....
}
client.Close();
}
catch (IOException e)
{
client.Close();
}
}
}
idAddress
is presumably a typo \$\endgroup\$async void
doesn't work. It should beasync Task
. haacked.com/archive/2014/11/11/async-void-methods \$\endgroup\$