有没有办法改善TCP连接时间
本文关键字:TCP 连接时间 有没有 | 更新日期: 2023-09-27 18:32:21
我编写了一个TCP服务器来使用BeginAccept/EndAccept模式。有了这个,我使用TcpClient编写了一个简单的单元测试,并测量了每个部分。所有测试都是本地主机,所以我惊讶地看到 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 秒以上。
不知道为什么,但只需更改一下:
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 秒。将不得不调查原因,但希望这将在未来帮助某人。
当您尝试在解析为 Ipv6 和 Ipv4 地址的主机上使用 TcpClient 构造函数进行连接时,将首先尝试使用 Ipv6 进行连接。如果失败,则尝试使用 Ipv6 地址进行连接。这是 1 秒延迟的原因。以下是 MSDN 链接: