Saturday, November 22, 2008

Connecting using Socket vs WebRequest.GetResponse

A web team in the company where I work, had deployed a web service on two different locations to, sort of, balance the load - but in reality it was actually only making one box function as a backup for the other. They had written one common Function which retrieves the web service from either of these two locations after confirming that they are up and alive.

The function was a bit slow in its response and when it was monitored during the fine tuning phase, we were looking for alternatives to the GetResponse. I did a simple page that calls a function that loops the GetResponse to the web server and noticed that it kept failing intermittently at times for no reason and it was awfully slow.

So much for just knowing if the box is up seemed a bit too much to leave it as it is. So the failover logic was made to be based on Sockets rather than the GetResponse. What I changed it to, was to just check if the web server box was up and active in the specific given port where we have the web service running. It seemed to be a better bargain for the given situation. Here is the sample function I asked them to use:

Partial Class ServerConnectivity

Private Shared Function TryConnectingSocket(ByVal serverName As String, ByVal port As Integer) As Boolean

Dim hostEntry As IPHostEntry = Nothing
Dim result As Boolean = False
Dim ipep As IPEndPoint = Nothing
Dim dummySocket As Socket = Nothing

' Get hostEntry from server IP passed
hostEntry = Dns.GetHostEntry(serverName)

' Loop through all the IP Addresses (would be just one if you passed in the IP Address itself)
For Each ip As IPAddress In hostEntry.AddressList

ipep = New IPEndPoint(ip, port)

' Create a dummy Socket object to ping and specify the timeouts and NoDelay properties
dummySocket = New Socket(ipep.AddressFamily, SocketType.Stream, Sockets.ProtocolType.Tcp)

With dummySocket
.NoDelay = True
.SendTimeout = 1000
.ReceiveTimeout = 1000
End With


' Try connecting using the endpoint which maps the port

If dummySocket.Connected Then

result = True


Continue For

End If

Catch ex As Exception
result = False

dummySocket = Nothing

End Try


Return result
End Function

End Class
Post a Comment