Stopping a TcpListener after calling BeginAcceptTcpClient

前端 未结 5 654
花落未央
花落未央 2021-01-31 18:38

I have this code...

internal static void Start()
{
    TcpListener listenerSocket = new TcpListener(IPAddress.Any, 32599);
    listenerSocket.Start();
    listen         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-31 19:29

    i think that all tree things are needed and that the restart of BeginAcceptTcpClient should be placed outside the tryctach of EndAcceptTcpClient.

        private void AcceptTcpClientCallback(IAsyncResult ar)
        {
            var listener = (TcpListener)ar.AsyncState;
    
            //Sometimes the socket is null and somethimes the socket was set
            if (listener.Server == null || !listener.Server.IsBound)
                return;
    
            TcpClient client = null;
    
            try
            {
                client = listener.EndAcceptTcpClient(ar);
            }
            catch (SocketException ex)
            {
                //the client is corrupt
                OnError(ex);
            }
            catch (ObjectDisposedException)
            {
                //Listener canceled
                return;
            }
    
            //Get the next Client
            listener.BeginAcceptTcpClient(new AsyncCallback(AcceptTcpClientCallback), listener);
    
            if (client == null)
                return; //Abort if there was an error with the client
    
            MyConnection connection = null;
            try
            {
                //Client-Protocoll init
                connection = Connect(client.GetStream()); 
            }
            catch (Exception ex)
            {
                //The client is corrupt/invalid
                OnError(ex);
    
                client.Close();
            }            
        }
    

提交回复
热议问题