(C#)这里我创建了一个等待客户端命中的套接字监听器应用程序。现在我的要求是我的应用程序应该只听到30秒后它应该抛出一个错误说“请求超时”。有什么建议吗?
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);
}
答案 0 :(得分:2)
我认为将ReceiveTimeout属性设置为30秒会为您处理。你试过了吗?
client.ReceiveTimeout = 30000;
该属性默认为0,因此您需要设置该属性。它抛出IOException。你可以抓住它并抛出你选择冒泡应用程序的例外。
答案 1 :(得分:0)
为什么要限制服务器监听的时间?
服务器应该一直在监听它正在运行。
无论如何,您可以创建一个正在侦听的任务(线程),并在超时后取消。