套接字等待接受关闭堆栈

时间:2014-12-20 18:59:57

标签: c# sockets

当我尝试关闭表单

时,我遇到问题

当我运行服务器时 并且线程启动套接字等待接受 然后我打开服务器 我尝试关闭服务器 这不可以, 它堆叠在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);
            }
        }
    }

1 个答案:

答案 0 :(得分:4)

不要试图杀死线程。只需针对服务器调用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
            }
        }
    }