I am writing a VB.NET app that connects to a legacy application using TCP.
The communication is working fine and is very quick once connected, but there is always a delay (of around 2.5-3.5 seconds) when I create the new connection even though I am connecting to my local machine:
Private _client As TcpClient
Public Property PortNumber As Int32 = 3338
Public Property ServerName As String = [Local machine name]
_client = New TcpClient(ServerName, PortNumber) ' <- takes some time to execute this line
Can someone suggest any improvement to this?
It’s probably a name resolution problem. If you’re happy that the IP address corresponding to the machine name won’t change during the lifetime of the application, you can resolve it first and store the IPAddress.
The way that TcpClient does this is by calling
Dns.GetHostAddresses(hostname)and then picking a suitable address from the list it gets back (e.g. it chooses an IPv4 address if you’re using an IPv4 socket).Have a look at the source for TcpClient for an example – once you’ve obtained the IP address you can continue to use TcpClient in the same way.
A TCP connection is always going to be quite an expensive thing to create (milliseconds though, not seconds), so if you’re making really large numbers of very short-lived connections, TCP might not be the best choice. This is why protocols like NTP and DNS are generally UDP-based, and why people try to make some effort to reuse connections for HTTP.