这是我运行服务器的方式:
public bool runServer()
{
try
{
soket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(IPAddress.Any, 10000);
soket.Bind(ep);
ThreadStart ts = listening;
Thread nit = new Thread(ts);
nit.IsBackground = true;
nit.Start();
return true;
}
catch (Exception)
{
return false;
}
}
稍后在listening
方法中,我将每个新客户端添加到列表中:
void listening()
{
try
{
while (true)
{
soket.Listen(50);
Socket client = soket.Accept();
clients.Add(client);
NetworkStream stream = new NetworkStream(client);
BinaryFormatter formatter = new BinaryFormatter();
//rest of method body
现在,我想创建一种方法,该方法将遍历列表clients
的每个元素,即List<socket>
,并与服务器断开连接,然后关闭服务器表单。但是我不确定该怎么做?要断开连接的客户端的连接,关闭服务器并关闭Windows窗体,必须执行哪些步骤?