gpt4 book ai didi

c# - 套接字等待接受关闭堆栈

转载 作者:行者123 更新时间:2023-11-30 20:45:55 26 4
gpt4 key购买 nike

当我尝试关闭表单时遇到了这个问题

当我运行服务器时并且线程启动套接字等待接受在我打开服务器之后我尝试关闭服务器这不可以,它堆叠在 NewCon.Abort() 中;

请帮帮我

代码是:

 private void ServerOn_Click(object sender, EventArgs e)
{
sckServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sckServerSocket.Bind(new IPEndPoint(ip, port));
sckServerSocket.Listen(0);
bIsOn = true;
dicStudent = new Dictionary<Socket, Student>();
NewCon = new Thread(getNewConnection);
NewCon.Start();
}

public void getNewConnection()
{
while (true)
{
Socket sckReciveConnect = sckServerSocket.Accept();
dicStudent.Add(sckReciveConnect, new Student(sckReciveConnect, this));
}
}

private void ServerOut_FormClosing(object sender, FormClosingEventArgs e)
{
if (bIsOn)
{
try
{
---> NewCon.Abort();
sckServerSocket.Close();

foreach (Student stu in dicStudent.Values)
{
byte[] Close = Encoding.Default.GetBytes("EXT");
stu.scksReciveSocket.Send(Close, 0, Close.Length, 0);
}

this.Close();
}
catch (Exception x)
{
MessageBox.Show(x.Message);
}
}
}

最佳答案

不要试图杀死线程。只需对服务器调用 Close(),这将导致阻塞的 Accept() 调用退出并出现异常:

// NewCon.Abort(); <-- don't do this
sckServerSocket.Close(); // just close it

您可以捕获它并跳出循环:

    public void getNewConnection()
{
while (true)
{
try
{
Socket sckReciveConnect = sckServerSocket.Accept();
// ...
}
catch (Exception)
{
return; // drop out of loop
}
}
}

关于c# - 套接字等待接受关闭堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27583362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com