【发布时间】:2020-04-19 05:48:58
【问题描述】:
我有以下代码:
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();
}
}
还是其他方式?谢谢。
【问题讨论】:
-
没有。该链接是关于检查套接字是否还活着,我问是否有一个套接字挂起。
标签: c# multithreading sockets tcplistener