TcpClient超时c#

时间:2018-04-13 09:39:21

标签: c# tcpclient

我将c#和TcpClient类与localhost一起使用,它在我的计算机上运行正常但是当计算机运行缓慢时它不起作用,因为"在一段时间后没有正确响应时间",我用Clumsy模拟这个"滞后"在我的计算机中,如果对localhost的正常ping是3ms,Clumsy可以是50ms,那么我的应用程序就无法工作。

我的代码:

public static MyClass connect()
{

        byte[] buffer = new byte[2048];
        TcpClient tcpClient = new TcpClient();
        tcpClient.SendTimeout = 10000;
        tcpClient.ReceiveTimeout = 10000;
        try
        {
            tcpClient.Connect("localhost", MY_PORT);
            NetworkStream stream = tcpClient.GetStream();
            stream.Write(Encoding.ASCII.GetBytes(TESTstring), 0, TESTstring.Length);
            stream.Read(buffer, 0, buffer.Length);
            string response = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
            stream.Close();
            MyClass m = JsonConvert.DeserializeObject<MyClass>(response);

            return m;
        }
        catch (Exception e){
            throw new TimeoutException();
        }
    }

我尝试使用异步连接但是在使用GetStream时崩溃,因为套接字已关闭。 (tcp.Connected = false

 using (TcpClient tcp = new TcpClient())
 {
      IAsyncResult ar = tcp.BeginConnect("localhost", MY_PORT, null, null);
      System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
      try
      {
         if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(30), false))
         {
             tcp.Close();
             throw new TimeoutException();
         }
         MessageBox.Show("OK");

         NetworkStream stream = tcp.GetStream(); -> CRASH

0 个答案:

没有答案