TcpClient连接到远程主机&应用冻结c#

时间:2016-10-26 10:39:31

标签: c# tcpclient

我正在尝试通过IP地址和端口号建立与远程主机的连接。连接确实已建立(甚至使用cmd netstat进行验证)但是当我尝试在代码中关闭连接时:

clientConnection.Client.Close();
clientConnection.Client.Dispose();
clientConnection.Close();

程序崩溃,因为套接字没有要从客户端流中读取的任何可用数据。在我的Windows应用程序(客户端)中,我有一个按钮,我单击该按钮调用ConnectToFalcon方法并调用ReadStream方法。请让我知道我哪里出错了。

  public void readStream(object argument)
    {

            clientConnection = (TcpClient)argument;
            //TcpClient client = new TcpClient();

            DateTime start_time = DateTime.Now;
            TimeSpan delay = new TimeSpan(0, 0, 10);
            while (clientConnection.Available == 0)
            {
                Application.DoEvents();
                if (DateTime.Now.Subtract(start_time) > delay)
                    break;
            }


            if ((clientConnection != null) && (clientConnection.Available > 0))
            {
                var message = new byte[1];
                Array.Resize(ref message, clientConnection.Available);
                //remove below two lines and if-statement block if program crashes
                clientConnection.Client.ReceiveTimeout = 20000; //Timeout after 20 seconds
                clientConnection.SendTimeout = 20000;
                if (clientConnection.Client.ReceiveTimeout <= 20000 || clientConnection.SendTimeout == 20000)
                {
                    clientConnection.Client.Receive(message);
                    string testResult = System.Text.Encoding.Default.GetString(message);
                }
                else
                {
                    MessageBox.Show("Time expired before read operation completed.");
                }
            }
            else if (((clientConnection == null) && (clientConnection.Available <= 0)) || (clientConnection.Connected == false))
            {
                clientConnection.Close();
                MessageBox.Show("Closing client connection due to insufficient amount of data available to be read");
            }

            //clientConnection.Client.Close();
            //clientConnection.Client.Dispose();
            //clientConnection.Close();
        }}


  public void ConnectToFalcon(string IPaddress, int port)
    {

            clientConnection = new TcpClient();
            //var result = clientConnection.BeginConnect(IPaddress, port, new AsyncCallback(callback), clientConnection);
            var result = clientConnection.BeginConnect(IPaddress, port, null, null);
            var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));

            if (success == false)
            {
                MessageBox.Show("Failed to connect");
            }
            else
            {
                MessageBox.Show("Client connected...");
                while (true)
                {
                    Thread t = new Thread(readStream);
                    t.Start(clientConnection); //A new thread is spawned
                    //t.Start();
                }
            }       
    }

enter image description here

1 个答案:

答案 0 :(得分:1)

根据@Luaan,您必须在回调函数中的IAsyncResult上调用EndConnect以确认客户端请求。

    public void callback(IAsyncResult ar)
    {
        this.clientConnection.EndConnect(ar);
    }

    var result = clientConnection.BeginConnect(ip, port, new AsyncCallback(callback), clientConnection);