我有以下代码:
class MyServer
{
TcpListener myList;
Socket socket;
public MyServer(string ip)
{
this.myList = new TcpListener(ip, 12001);
this.myList.Start();
Thread t = new Thread(new ThreadStart(GetConnection));
t.Start();
}
public void GetConnection()
{
try
{
socket = myList.AcceptSocket(); //(1)
}
catch
{
Console.WriteLine("Error");
}
}
public void StopListening()
{
this.myList.Stop();
}
}
它运行良好:我启动服务器,如果我“后悔”,我会调用StopListening()(在建立连接之前!),并且由于我关闭myList,所以(1)失败了。
有没有任何方法可以不用try {} catch {}编写此代码-将GetConnection()重写为:
public void GetConnection()
{
while ( myList is open && there is no connection)
{
//do nothing
}
if (myList is open)
{
this.socket = myList.AcceptConnection();
}
}
还是另一种方式?谢谢。
答案 0 :(得分:0)
socket = myList.AcceptSocket()
这是一个阻塞的调用,因此如果基础套接字停止侦听,它将引发异常,因此您仍然需要对该try / catch进行阻塞调用。
您可以测试:
if (myList.Server.IsBound)
{
this.socket = myList.AcceptConnection();
}
这样,除非套接字正在积极侦听,否则您不会阻塞下一个连接。但是就像我说的那样,如果您希望程序能够在某个时候停止监听,那么在调用myList.Stop()