Beispiel #1
0
        ///<summary>
        /// 当客户链接等待传入时被调用。
        /// 关闭监听器时,也被调用,只不过EndAcceptTcpClient会触发异常
        /// </summary>
        ///<param name="ar">异步操作的结果</param>
        private void OnAccept(IAsyncResult ar)
        {
            TcpClient tcp = null;

            try
            {
                tcp = TcpServer.EndAcceptTcpClient(ar);
            }
            catch { return; }
            try
            {
                // 先重新开始监听,不要耽误了别的来访者访问
                TcpServer.BeginAcceptTcpClient(new AsyncCallback(this.OnAccept), TcpServer);
            }
            catch { Dispose(); }
            try
            {
                if (tcp != null)
                {
                    NetHelper.SetKeepAlive(tcp.Client, true, 30000, 30000);
                    Session NewClient = OnAccept(tcp);
                    if (Config.IsShow && OnWriteLog != null)
                    {
                        NewClient.OnWriteLog += new WriteLogDelegate(WriteLog);
                    }
                    NewClient.OnDestroy += new DestroyDelegate(ClientDestroy);
                    NewClient.Listener   = this;
                    NewClient.WriteLog("新客户 (" + tcp.Client.RemoteEndPoint.ToString() + ")");
                    Clients.Add(NewClient);
                    NewClient.Start();
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine("监听器接受连接时出错! " + ex.Message);
            }
        }