Issue using MS Winsock control in VB6

I have a VB 6 app that recieves data from another machine. Right now I can recieve data the machine is sending and send back an Ack to the sending machines port number. The issue is I want to use another port number to send the ack to the sending machine.  Doing something like this tcpServer.RemotePort = 3000 does not work since I cannot change the remote port number while the connection is open. I tried to close the current connection then open a scond one (second winsock control on the form but when it hits the TCPserver2.Connect statement it fails with "Address already in use" even thuogh I have closed the previous connection.
Who is Participating?
jkaiosIT DirectorCommented:
A better solution to that is to create a "control array" for the Winsock control and put it as control array 0.
When you first make a connection to the remote machine, you load a second instance of the control and assign it to port 0.
Using Port 0 (zero) will cause the Winsock control to dynamically select an unused port on the local machine.
This will then be the port that the local machine will communicate with the remote machine in any subsequent communication.

The remote machine, on the other hand, must also have a control array and will have to load a second instance to accept
incoming connection requests in the ConnectionRequest event of the Winsock control.

In your connection sub-routine, try this:
  m_iSockets = m_iSockets + 1
  Load Wsock(m_iSockets)
  Wsock(m_iSockets).LocalPort = 0
  Wsock(m_iSockets).Connect "The-Remote-Machine", "3000"

In the "ConnectionRequest" of the Winsock control, you will also have to load
a second instance of the control as follows to accept the incoming connection.
 m_iSockets = m_iSockets + 1
 Load Wsock(m_iSockets)
 Wsock(m_iSockets).Accept requestID

The "m_iSockets" variable keeps all the current connections made so far, so
be sure the loop thru when attempting to close all connections to get a clean
disconnect and free up any memory allocations.
  If m_iSockets >= 1 Then
     For ii = 1 To m_iSockets
       Unload Wsock(m_iSockets)
     m_iSockets = 0
  End If
  ' Close whatever connection is still active
  For ii = Wsock.LBound To Wsock.UBound

you should add a delay because the other computer has to respond to your connection close
jkaiosIT DirectorCommented:
... Your remote machine (server) just sits and listens for incoming connections on port 3000, but when sending/receiving ACK to/from
"client" machines, must be on a different port.  This is to keep the listening port (3000) open for any new incoming connections.

In this way, the server can accept multiple connections simultaneously.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.