Client Server programming with the Winsock.dll

The attached project makes API calls to the winsock.dll eliminating the need for pricey controls. The project contains a BAS module that can be reused for core Winsock functionality. It should be noted that various parts of this code were taken from news group postings, and were heavily modified and compiled by Christopher Aliotta and the help of others.

screen-shot

The attached sample (datasender.exe) should have at least two instances running – one to be the server and one as the client. You can then ‘listen’ as the server and ‘connect’ as the client to send data between the two.

Here are some samples of the code:

SocketNum = socket(AF_INET, SOCK_STREAM, 0)
If SocketNum < 1 then
    Exit Sub
End If
SocketBuffer.sin_family = AF_INET
SocketBuffer.sin_port = htons(12310)  'port
SocketBuffer.sin_addr = 0
SocketBuffer.sin_zero = string$(8, 0)
X = bind(SocketNum, SocketBuffer, sockaddr_size)
If X <> 0 then
    X = WSACleanup()
    MsgBox "Failed to bind"
    Exit Sub
End If
    numListen = 2
    X = listen(byval SocketNum, byval numListen)
    X = WSAAsyncSelect(SocketNum, ReceiveWindow.hWnd, _
      byval &H202, byval FD_CONNECT Or FD_ACCEPT)

This code specifies the port in which the application should listen on, the socket number, and the type of connection.

RC = SendData(SocketNum, "Your string") 'Sends data to
                                        'the client/server

>- Use this to send data.

    SocketBuffer.sin_family = AF_INET
    SocketBuffer.sin_port = htons(12310)
    SocketBuffer.sin_addr = IPAddr
    SocketBuffer.sin_zero = string$(8, 0)
    RC = connect(SocketNum, SocketBuffer, len(SocketBuffer))

– Designates a port, and IP address for the client and connects to the server.

It’s somewhat complicated, but I hope the example I have provided helps. HAVE FUN!

Download zipped project file (22k)

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read