我希望我的服务器在没有连接请求的情况下在一分钟后停止收听。 问题是在命令AcceptTcpClient()之后它进入一个循环,没有选项来阻止它。 可以选择这样做吗?
private static void Listen(TcpListener listener)
{
//Start listening
listener.Start();
Console.WriteLine("Waiting for a connection...\n");
//Accept connection
TcpClient client = listener.AcceptTcpClient();
//Need to stop it after 1 minute.
listener.Stop();
//CHECK
Console.WriteLine("Accepted the connection\n");
ClientHandle(client);
}
答案 0 :(得分:0)
有几种方法可以做到:
1)异步等待而不阻塞线程:
private static async Task Listen(TcpListener listener)
{
//Start listening
listener.Start();
Console.WriteLine("Waiting for a connection...\n");
//Accept connection
TcpClient client = listener.AcceptTcpClient();
await Task.Delay(60000); // async wait for 1 minute
listener.Stop();
//CHECK
Console.WriteLine("Accepted the connection\n");
ClientHandle(client);
}
不要忘记等待来自调用方的这个方法:
await Listen(yourListener);
2)使用Timer (System.Threading.Timer)
:
private static void Listen(TcpListener listener)
{
//Start listening
listener.Start();
var timerTimer = new Timer((state) => { listener.Stop(); }, null, 60000, Timeout.Infinite);
Console.WriteLine("Waiting for a connection...\n");
//Accept connection
TcpClient client = listener.AcceptTcpClient();
//CHECK
Console.WriteLine("Accepted the connection\n");
ClientHandle(client);
}
您还可以使用任何其他计时器。
答案 1 :(得分:-1)
TcpListener server = new TcpListener(......);
TcpClient client = null;
int timeout = 30000;//30 sec
server.Start();
using(CancellationTokenSource tokenSource = new CancellationTokenSource(timeout))
{
using(tokenSource.Token.Register(() => server.Stop()))
{
client = server.AcceptTcpClient();
//don't code here, need dispose Token.Register if Accept success
}
}
//todo here