• [转]c# winform tcp connect timeout 连接超时设置


    转自:https://www.cnblogs.com/jhlong/p/5622336.html

    简单的c# TCP通讯(TcpListener)

    C# 的TCP Socket (同步方式)

    C# 的TCP Socket (异步方式)

    C# 的tcp Socket设置自定义超时时间

    C# TCP socket发送大数据包时,接收端和发送端数据不一致 服务端接收Receive不完全

    方式一

    tcp Socket的超时时间默认20多秒,而实际连上不需1秒时间,20多秒是无法接受的。

    private delegate string ConnectSocketDelegate(IPEndPoint ipep, Socket sock);
    private string ConnectSocket(IPEndPoint ipep, Socket sock)
    {
    string exmessage = "";
    try
    {
    sock.Connect(ipep);
    }
    catch (System.Exception ex)
    {
    exmessage = ex.Message;
    }
    finally
    {
    }

    return exmessage;
    }
    private void button5_Click_1(object sender, EventArgs e)
    {

    IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.18.165"), 9961);//IP和端口
    Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    ConnectSocketDelegate connect = ConnectSocket;
    IAsyncResult asyncResult = connect.BeginInvoke(ipep, sock, null, null);

    bool connectSuccess = asyncResult.AsyncWaitHandle.WaitOne(2000, false); //2秒后结束
    if (!connectSuccess)
    {
    MessageBox.Show(string.Format("失败!错误信息:{0}", "连接超时"));//2秒后弹出

    }

    string exmessage = connect.EndInvoke(asyncResult); //此处仍然会卡住20多秒,可注释掉
    if (!string.IsNullOrEmpty(exmessage))
    {
    MessageBox.Show(string.Format("失败!错误信息:{0}", exmessage));

    }

    }

    方式二:修改注册表(亲测有效)

    HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesTcpipParameters

    Value Name:  TcpMaxDataRetransmissions
    Data Type: REG_DWORD - Number
    Valid Range: 0 - 0xFFFFFFFF
    Default: 2 (默认值5 修改为2)

    Description: This parameter controls the number of times TCP retransmits an individual data segment (non connect segment)
    before aborting the connection. The retransmission time-out is doubled with each successive retransmission on a connection.
    It is reset when responses resume. The base time-out value is dynamically determined by the measured round-trip time on the connection.


    Value Name:  InitialRttData 
    Type: REG_DWORD
    Valid Range: 0-65535 (decimal)
    Default: 0x5dc (1500毫秒 默认值 0xBB8 (3000 decimal) )
    Description: This parameter controls the initial retransmission time-out used by TCP on each new connection. It applies to the connection request (SYN) and to the first data segment(s) sent on each connection.

    超时时间大概是2*1.5s
    来源 https://support.microsoft.com/en-us/help/170359/how-to-modify-the-tcp-ip-maximum-retransmission-time-out
  • 相关阅读:
    推箱子
    为textarea增加maxlength属性(转)
    validate
    keypress
    Knockout
    & replace &
    银联参数
    chinapay
    model binding
    JSON.stringify
  • 原文地址:https://www.cnblogs.com/xuejianxiyang/p/10191739.html
Copyright © 2020-2023  润新知