I am trying to catch all incoming events on a specific Port. It works fine but i think, my Socket is blocked for 5s while stream.Read()
is performing. What could happen if a package enters while stream.Read()
is busy? And how could i avoid possible dataloss?
public static void Main(string[] args)
{
System.Console.WriteLine("Testprogramm Connection\n");
//ThreadListener tl = new ThreadListener();
DateTime startTime3 = DateTime.Now;
DateTime startTime4 = DateTime.Now;
TimeSpan duration3;
TimeSpan duration4;
while (true)
{
DataPackage dp = Connection.readEvent(4002, 3000);
DateTime EndZeit = DateTime.Now;
if (dp.Ip.Equals("192.168.101.3"))
{
duration3 = EndZeit - startTime3;
System.Console.WriteLine("Duration to last receive: " + duration3);
startTime3 = DateTime.Now;
}
if (dp.Ip.Equals("192.168.101.4"))
{
duration4 = EndZeit - startTime4;
System.Console.WriteLine("Duration to last receive: " + duration4);
startTime4 = DateTime.Now;
}
System.Console.WriteLine();
}
}
...Connection.cs
public static DataPackage readEvent(int port, int size)
{
DataPackage dp = new DataPackage();
byte[] bytes = new byte[size];
String ip_client = "";
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[1];
try
{
System.Console.Write("Wait...:");
listener = new TcpListener(ipAddress, port);
listener.Start();
tcpClient = listener.AcceptTcpClient();
tcpClient.NoDelay = true;
tcpClient.Client.NoDelay = true;
ip_client = tcpClient.Client.RemoteEndPoint.ToString();
stream = tcpClient.GetStream();
DateTime startTime = DateTime.Now;
stream.Read(bytes, 0, bytes.Length);
DateTime endTime = DateTime.Now;
stream.Close();
tcpClient.Close();
listener.Stop();
dp.Data = bytes;
dp.setIP(ip_client);
System.Console.Write("...received from " + ip_client + " busy:");
TimeSpan duration = endTime - startTime;
System.Console.WriteLine(duration.Seconds + "s");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
closeAllConnections();
return null;
}
return dp;
}
I'm not surprised that you're seeing the inter-event delays. In your readEvent method, you're creating the sockets, then listening for an incoming connection, then performing your read() then closing all the sockets. It takes a little bit of time to set up your sockets. Its a better approach if you make the sockets members of your connection class, doing an initialization - create, listen, connect - and then in your readEvent method you would retrieve messages. A fancier approach might be to queue up all the events so that clients of your connection could just go and pick them up, but that involves a little asynchronous programming.