我有以下代码: 它运行良好:我启动服务器,如果我“后悔”,我会调用StopListening()(在建立连接之前!),并且由于我关闭myList,所以(1)失败了。 有没有任何方法可以不用try {} catch {}编写此代码-将GetConnection()重写为: 还是另一种方式?谢谢。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();
}
}
public void GetConnection()
{
while ( myList is open && there is no connection)
{
//do nothing
}
if (myList is open)
{
this.socket = myList.AcceptConnection();
}
}
0 个答案:
没有答案