日期:2014-05-17  浏览次数:20788 次

异步的TCP服务器程序
我做了个TCP服务器程序,用来监听各个客户端的连接,并与之通信。照着书上用异步的方式写了程序,以下是代码。


        private void AcceptConnect() 
        {
            IPAddress[] ip = Dns.GetHostAddresses(Dns.GetHostName());
            listener = new TcpListener(ip[0], 51888);
            listener.Start();
            listBoxStatus.Invoke(setListBoxCallback, "开始等待客户连接");
            while (isExit == false) 
            {
                try 
                {
                    allDone.Reset();
                    AsyncCallback callback = new AsyncCallback(AcceptTcpClientCallback);
                    listener.BeginAcceptTcpClient(callback,listener);
                    allDone.WaitOne();
                }
                catch (Exception ex) 
                {
                    listBoxStatus.Invoke(setListBoxCallback,ex.Message);
                    break;
                }
            }
        }

        private void AcceptTcpClientCallback(IAsyncResult ar) 
        {
            try 
            {
                allDone.Set();
                TcpListener myListener = (TcpListener)ar.AsyncState;
                TcpClient client = myListener.EndAcceptTcpClient(ar);
                listBoxStatus.Invoke(setListBoxCallback, "已接受客户连接:" +                       client.Client.RemoteEndPoint);
         &