C# 如果没有响应,请在30秒后关闭套接字侦听器应用程序
(C#)在这里,我创建了一个套接字侦听器应用程序,它等待客户端命中。现在我的要求是,我的应用程序应该最多监听30秒,然后它应该抛出一个错误,说“请求超时”。有什么建议吗C# 如果没有响应,请在30秒后关闭套接字侦听器应用程序,c#,.net,C#,.net,(C#)在这里,我创建了一个套接字侦听器应用程序,它等待客户端命中。现在我的要求是,我的应用程序应该最多监听30秒,然后它应该抛出一个错误,说“请求超时”。有什么建议吗 try { Byte[] bytes = new Byte[256]; String data = null; // Enter the listening loop. while (true)
try
{
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
ReceiveTimer.Stop(); ;
logger.Log("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also use server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
logger.Log("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
logger.Log("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
logger.Log("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
logger.Log("Shutdown and end connection");
}
}
catch (SocketException ex)
{
logger.Log("SocketException: " + ex);
}
我认为将ReceiveTimeout属性设置为30秒可以为您解决这个问题。你试过了吗
client.ReceiveTimeout = 30000;
该属性默认为0,因此您需要设置该属性。它抛出一个IOException。您可以捕捉到这一点,并抛出选择使应用程序冒泡的异常。为什么要限制服务器侦听的时间 服务器在运行时应该一直在侦听
无论如何,您可以创建一个正在侦听的任务(线程),超时后将被取消。我希望client.ReceiveTimeout属性在任何客户端命中侦听器后都会超时,但我的要求是停止侦听器,而不管客户端请求如何。