有没有办法改善TCP连接时间?

时间:2012-04-27 06:53:42

标签: c# sockets tcp connection performance-testing

我写了一个TCP服务器来使用BeginAccept / EndAccept模式。有了这个,我使用TcpClient编写了一个简单的UnitTest,并测量了每个部分。所有测试都是localhost,所以我很惊讶地发现TCP连接始终需要1秒钟。我设置了Socket.NoDelay = true,但我相信这只会影响发送/接收。我没有收到第一个数据包。任何有关速度的帮助或想法都值得赞赏。

注意:我无法更改客户端以保持连接打开,如果可能,我需要能够每秒处理大量请求。

服务器端:

public void Start()
{
    System.Net.IPHostEntry localhost = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
    System.Net.IPEndPoint endpoint;
    int port = Properties.Settings.Default.ListenPort;

    //
    // Setup the connection to listen on the first IP, and specified port
    //
    endpoint = new IPEndPoint(IPAddress.Any, port);
    listenSocket = new Socket(endpoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
    listenSocket.Bind(endpoint);
    listenSocket.NoDelay = true; // do not wait 200 milliseconds for new data to be buffered on the connection
    listenSocket.Listen(int.MaxValue);
    Console.WriteLine("Listening on {0}:{1}", localhost.AddressList[0], port);

    //
    // Post the accept. The accept method will continuously post a new accept as soon as a connection is made
    //
    while (true)
    {
        accepted.Reset();
        Connection connection = connections.Pop();
        listenSocket.BeginAccept(AcceptCallback, connection);
        accepted.WaitOne();
    }
}

private static void AcceptCallback(IAsyncResult ar)
{
    accepted.Set();

    Connection connection = ar.AsyncState as Connection;
    Socket remoteSocket = null;

    try
    {
        remoteSocket = listenSocket.EndAccept(ar);
        remoteSocket.NoDelay = true;                
        connection.RemoteSocket = remoteSocket;

        //
        // Start the Receive cycle
        //
        Receive(connection);             
    }
    catch (SocketException)
    {
        Disconnect(connection);
    }           
}

简单测试客户端:

[TestMethod()]
public void ClientTest()
{
    TestContext.BeginTimer("Connection");
    TcpClient client = new TcpClient("localhost", 10300);
    NetworkStream stream = client.GetStream();
    TestContext.EndTimer("Connection");
    ...

使用LoadTest我加载了25个用户,而事务“连接”总是需要1秒以上。

2 个答案:

答案 0 :(得分:4)

不确定原因,只是改变了这一点:

TestContext.BeginTimer("Connection");          
TcpClient client = new TcpClient("localhost", 10300);            
TestContext.EndTimer("Connection");

对此:

TestContext.BeginTimer("Connection");
TcpClient client = new TcpClient();
client.Connect("localhost", 10300);       
TestContext.EndTimer("Connection");

将时间从1秒减少到.13秒。将不得不调查为什么,但希望这将有助于某人将来。

答案 1 :(得分:3)

当您尝试在解析为Ipv6和Ipv4地址的主机上使用TcpClient构造函数进行连接时,首先尝试使用Ipv6进行连接。如果失败,则尝试使用Ipv6地址进行连接。这是1秒延迟的原因。 Here is the MSDN link