Recently I have been experimenting with Sockets and trying to communicate with a windows service both with a console app and a website.
After managing to get some lines of communication going between the client and server applications, I couldn’t help but notice that it was taking a little bit longer than it probably should have. I decided to have a closer look.
Using some basic timestamping in the console/website application the whole process was taking just over 1 second. This was to connect, send and then receive a response. Further investigation revealed only 1 statement was causing the time to blow out. Below is the statement.
TcpClient socketForServer = new TcpClient("localhost", 200);
Now in all the demos and tutorials this is how it showed to connect to the server. Pretty straightforward and simple. Or so I thought. Whilst having a look through the methods associated with the TcpClient, there was one that stood out: Connect(). Hmmm…this also took a host name and a port. I decided to give it a try.
I bet you’re wondering right now. What is the difference?? At this point in time I’m not quite sure but I’m determined to figure it out because after making that change the time to execute the previous two statements was about 1 millisecond or so. Much better.
One thing that did seem odd was if the TcpClient failed to make a connection, the response time was almost exactly the same (~1sec).
If anyone knows the reason, please leave a comment. Until then, two lines will have to do.