I'm working on a legacy VB6 app. The app uses the RAS API to establish a modem connection, then uses a winsock control to connect to an IP address & port.
I'm now adding a "failover" feature to this app where if it can't connect to a server, it tries to connect to the next one in the list.
Let's say I have two servers, server app A and server app B. (During my tests I've swapped these around to verify that both servers are accessible and there are no routing / firewall issues.)
If I stop server app A, then something quite strange happens when the app tries to connect to server app A and then server app B:
mySocket.close
mySocket.Connect serverA, portA
(which seems slightly odd: I'm not sure why it appears to connect for a few moments.)
The socket remains in sckClosing state. After a few hundred milliseconds I move on to try to connect to server B:
mySocket.close
.
mySocket.Connect serverB, portB
At this point if I start server app A, do a RAShangup and a RASdial, and try to connect to server A, all works OK.
It's as if the sequence
socket.connect ip, port
socket.close
socket.connect newIP, newPort
doesn't work properly unless a RAShangup and RASdial is inserted. Instead it fails with WSAETIMEDOUT.
Is there anything I need to do between a close and connect call?
Note: I've tried making sure that the close call has really closed, but this doesn't help:
Private Sub closeSocket(ByRef w As Winsock)
w.Close
Do While (w.State <> sckClosed)
DoEvents
Loop
End Sub
After looking again at the project, it turns out that a previous developer set the LocalPort property of the winsock control to a nonzero value. This was preventing the reuse of the winsock control.
Setting this to zero causes a random local port to be selected, which allows the control to be reused.
Lesson learned: when dealing with VB6 I need to look at the property settings as well as the source code.