开启了一个tcplistener监听,请问怎么才能将这个监听关闭呢?
监听ip和端口是在界面上实时填写的,因此在方法里才把tcplistener和tcpClient实例化,我觉得是不是这里,但不确定,请问下到底怎么释放监听的端口呢??部分代码如下:        private void threadstart()
        {
            string msg = "现在开始监听【" + this.txt_ip.Text + "】的" + "端口【" + this.txt_port.Text + "】";
            this.setLabelText(msg,true);
            this.setListText(msg,true);
            IPAddress ipadd = IPAddress.Parse(this.txt_ip.Text.Trim());
            int port = Convert.ToInt32(this.txt_port.Text.Trim());            try
            {                this.serverlistener = new TcpListener(ipadd, port);                this.serverlistener.Start();                while (isthread)
                {
                    Thread.Sleep(10);
                    tcpClient = serverlistener.AcceptTcpClient();
                    byte[] bytes = new byte[256];
                    string backstr = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
                }            }
            catch (Exception ex)
            {
                isthread = false;
                MessageBox.Show("系统发生错误:" + ex.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if(null != this.tcpClient)
                    this.tcpClient.Close();
                this.serverlistener.Stop();
            }
        }

解决方案 »

  1.   

    这是现在关闭的代码 但自己都觉得非常有问题        private void btn_close_Click(object sender, EventArgs e)
            {
                if (null != th)
                {
                    th.Abort();
                    string msg = "现在尚未开始任何监听";
                    this.setLabelText(msg, true);
                    this.setListText(msg, true);
                    this.setBtnStart("", true);
                    this.setBtnClose("", false);
                }
            }
      

  2.   

    我看到了
                finally
                {
                    if(null != this.tcpClient)
                        this.tcpClient.Close();
                    this.serverlistener.Stop();
                }这不就是释放的代码吗?显然你手动释放调用下就可以了。还有个循环while (isthread)
    最好先isthread=false后再去关闭。
      

  3.   

    这个代码出现报错:
    通常每个套接字地址 (协议 网络地址 端口 只允许使用一次)2楼说的th.disposed();当然可能可以,但这样强行释放会不会有其他问题出现呢?
      

  4.   

    怎么回呢?
    你都关闭侦听了,除非你再次start,否则客户端是连接不上服务器的啊;