【发布时间】:2019-05-11 03:29:43
【问题描述】:
在停止服务器并尝试重新启动后,我遇到了 TcpListener 类的问题。我基本上想做的是使用AcceptTcpClientAsync() 方法来处理传入的连接请求并提供重新启动服务器的可能性。
小例子:
class Program
{
private static TcpListener listener;
static void Main(string[] args)
{
StartServerAsync();
StopServer();
StartServerAsync();
Console.ReadKey();
}
private static void StopServer()
{
if (listener != null)
listener.Stop();
}
private async static void StartServerAsync()
{
listener = new TcpListener(IPAddress.Loopback, 1234);
listener.Start();
while (true)
{
var client = await listener.AcceptTcpClientAsync();
}
}
}
在第二次调用await listener.AcceptTcpClientAsync() 时,我收到了ObjectDisposedException 的套接字。
任何想法或意见如何克服这个问题?
谢谢!
【问题讨论】:
-
那是你的完整代码还是清理后的版本?您是否在循环中的某处执行“listener.Close()”?
-
@AnuViswan 这是完整的代码,我试图找出这个简化代码的问题
-
恕我直言,这是一个清理版本。然而,它抛出了所描述的异常。我的猜测是,它会在第一次调用停止之后执行此操作。但实际上它在第二个实例的最后一次等待调用中抛出。我也稍微改写了一下,并为每个实例使用了不同的端口(不是地址),但错误仍然存在。
标签: c# async-await tcplistener