using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;namespace AsyncServerWin
{
    public partial class Form1 : Form
    {
        int num = 0;
        EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.ManualReset);
        TcpListener tl = new TcpListener(IPAddress.Any, 9876);
        public Form1()
        {
            InitializeComponent();
        }        public void BeginListen()
        {
            try
            {
                tl.Start();
                AsyncCallback ac = new AsyncCallback(MyAcceptTcpClient);
                while (true)
                {
                    ewh.Reset();
                    tl.BeginAcceptTcpClient(ac, tl);
                    ewh.WaitOne();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                tl.Stop();
            }
        }
        
        private void button1_Click(object sender, EventArgs e)
        {
            this.button1.Enabled = false;
            Thread t = new Thread(BeginListen);
            t.Start();
            
        }        public void MyAcceptTcpClient(IAsyncResult ar)
        {
            try
            {
                ewh.Set();
                TcpListener tl = (TcpListener)ar.AsyncState;
                TcpClient tc = tl.EndAcceptTcpClient(ar);
                num++;
                lbConnectionID.Items.Add(((int)tc.Client.Handle).ToString());
                tbNum.Text = num.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                tl.Stop();
            }
        }        private void button2_Click(object sender, EventArgs e)
        {                tl.Stop();//---------------------------------------------------这里出问题了!!!
                this.button1.Enabled = true;
        }
    }
}================================================================================namespace AsyncServerWin
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }        #region Windows 窗体设计器生成的代码        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.tbNum = new System.Windows.Forms.TextBox();
            this.lbConnectionID = new System.Windows.Forms.ListBox();
            this.button2 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(167, 51);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "启动";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // tbNum
            // 
            this.tbNum.Location = new System.Drawing.Point(167, 133);
            this.tbNum.Name = "tbNum";
            this.tbNum.Size = new System.Drawing.Size(100, 21);
            this.tbNum.TabIndex = 1;
            // 
            // lbConnectionID
            // 
            this.lbConnectionID.FormattingEnabled = true;
            this.lbConnectionID.ItemHeight = 12;
            this.lbConnectionID.Location = new System.Drawing.Point(29, 133);
            this.lbConnectionID.Name = "lbConnectionID";
            this.lbConnectionID.ScrollAlwaysVisible = true;
            this.lbConnectionID.Size = new System.Drawing.Size(120, 88);
            this.lbConnectionID.TabIndex = 2;
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(167, 198);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 3;
            this.button2.Text = "停止";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.lbConnectionID);
            this.Controls.Add(this.tbNum);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();        }        #endregion        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox tbNum;
        private System.Windows.Forms.ListBox lbConnectionID;
        private System.Windows.Forms.Button button2;
    }
}

解决方案 »

  1.   

    又写了个同步的,更搞笑,为什么我一按关闭button2,整个窗体都没了,程序也结束了using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;namespace tcpserver
    {
        public partial class Form1 : Form
        {
            TcpListener tl = new TcpListener(IPAddress.Any, 8201);
            public Form1()
            {
                InitializeComponent();
            }        private void button1_Click(object sender, EventArgs e)
            {
                
                tl.Start();
                Thread th = new Thread(Fun);
                th.Start();        }        private void Fun()
            {
                TcpClient tc = tl.AcceptTcpClient();
            }        private void button2_Click(object sender, EventArgs e)
            {
                tl.Stop();
            }
        }
    }
      

  2.   

    2楼的问题我弄清楚了,原来是在AcceptTcpClient是调stop会有异常,原问题还没研究出来,麻烦大家啦
      

  3.   

    我换个问题问比较清楚,不然大家看到这么多代码都怕了,上面的问题不要回答了哦,就帮忙下面这个就好,再次感谢下啊我的问题跟以前某位仁兄问过的很相似,引用他的帖子吧http://topic.csdn.net/t/20061211/15/5222278.html简单的说就是就是在这个模型中
    FunOne()
    {...
    tl.BeginAcceptTcpClient(ac, tl);
    ...
    }FunTwo()
    {
    ...
    TcpListener tl = (TcpListener)ar.AsyncState;
    TcpClient tc = tl.EndAcceptTcpClient(ar);
    ...
    }FunThree()
    {
    listener.stop();
    }在调用了FunThree后,就是TcpListener已经被关闭了,断点跟踪后看到程序还是跳到了FunTwo里,就是说BeginAcceptTcpClient即使没有收到客户端连接,居然在listener stop以后也会调用它的回调函数,结果当然是出异常,说连接已经关闭,无法访问已释放的对象我就是想问,这个问题怎么解决呢
      

  4.   

    如果lz是在搞不清楚异步和线程的正确写法,建议仔细研究一下微软封装后的BackgroundWorker控件。估计这个比较适合入门。而且lz这点小问题,直接用这个控件简单明了。
      

  5.   

    顶一下.不过我还是不太明白
    上网站看下吧找找有没有你要的
    www.qzshi.com
      

  6.   

    你可以添加个状态变量,
    bool listenerrunning;
    修改下
    private void button2_Click(object sender, EventArgs e) 
            { 
                listenerrunning=false;
            } 再修改下
     public void MyAcceptTcpClient(IAsyncResult ar) 
            { 
                try 
                { 
                    ewh.Set(); 
                    if(listenerrunning)
                    {
                    TcpListener tl = (TcpListener)ar.AsyncState; 
                    TcpClient tc = tl.EndAcceptTcpClient(ar); 
                    num++; 
                    lbConnectionID.Items.Add(((int)tc.Client.Handle).ToString()); 
                    tbNum.Text = num.ToString(); 
                    }
                } 
                catch (Exception ex) 
                { 
                    MessageBox.Show(ex.ToString()); 
                    tl.Stop(); 
                } 
            } 
      

  7.   

    晕,怎么不能修改我的贴子
    上面的不全,应该是这样改
    private bool listenerrunning; public void BeginListen() 
            { 
                listenerrunning=true;
                try 
                { 
                    tl.Start(); 
                    AsyncCallback ac = new AsyncCallback(MyAcceptTcpClient); 
                    while (true) 
                    { 
                        ewh.Reset(); 
                        tl.BeginAcceptTcpClient(ac, tl); 
                        ewh.WaitOne(); 
                    } 
                } 
                catch (Exception ex) 
                { 
                    MessageBox.Show(ex.ToString()); 
                    tl.Stop(); 
                } 
            } private void button2_Click(object sender, EventArgs e)  
            {  
                listenerrunning=false; 
                tl.Stop();
            }  public void MyAcceptTcpClient(IAsyncResult ar)  
            {  
                try  
                {  
                    ewh.Set();  
                    if(listenerrunning) 
                    { 
                    TcpListener tl = (TcpListener)ar.AsyncState;  
                    TcpClient tc = tl.EndAcceptTcpClient(ar);  
                    num++;  
                    lbConnectionID.Items.Add(((int)tc.Client.Handle).ToString());  
                    tbNum.Text = num.ToString();  
                    } 
                }  
                catch (Exception ex)  
                {  
                    MessageBox.Show(ex.ToString());  
                    tl.Stop();  
                }  
            }  
      

  8.   

    while语句的判断也要改...整个代码,我也没测,以前做过,都忘了,不过肯定是有用的
    public void BeginListen()  
            {  
                listenerrunning=true; 
                try  
                {  
                    tl.Start();  
                    AsyncCallback ac = new AsyncCallback(MyAcceptTcpClient);  
                    while (true && listenerrunning)  
                    {  
                        ewh.Reset();  
                        tl.BeginAcceptTcpClient(ac, tl);  
                        ewh.WaitOne();  
                    }  
                }  
                catch (Exception ex)  
                {  
                    MessageBox.Show(ex.ToString());  
                    tl.Stop();  
                }  
            }