我正试图捕获特定端口上的所有传入事件。它工作正常,但我认为,我的Socket被阻塞5秒,而stream.Read()
正在执行。 stream.Read()
忙时,如果有包裹进入,会发生什么情况?我怎么能避免可能的数据丢失?C#在没有busyTimes的情况下在tcp网络中侦听?
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;
}
你能举个例子吗? –
我曾尝试尽可能提前启动。但没有注意到一些改进。我曾考虑过线程,但我认为使用套接字多次或连接到同一端口的多个套接字可能会有问题... –
我添加了一个可能遵循的示例。我在VS中很快就把它掀起来了,所以它应该可以编译,但它没有完全测试。你应该从中得到想法。 –