Multithread Winsock in Visual Basic

Posted on 2004-03-27
Medium Priority
Last Modified: 2013-11-25

    I would like to know if you can help me with a Multithread Winsock Application in Visual Basic 6.0
    If yes, could you send me an example? The project is like that:

    - Several threads (with its own winsock) will be listening the same port.
    - Would be great if threads were being created when new winsocks were necessary, but if your sample code came with a predefined number of threads, no problem!
    - When a connection request (or data) arrives; one free thread (or create a new thread) will handle this event and will connect to a database, grab some information and will send data through this socket again, will also receive data from this socket, doing a "hand shake", till a close event arrives.

     I would like something fast because the time is running and I'm about to be hang!!! I'm sure doing the project as described above I will survive... (I'm crazy about it, now is 11:04 PM GMT -3 ---> March, 27 of 2004 ++++ Saturaday night)


     Helton Ferreira
Question by:helton1
  • 6
  • 5

Expert Comment

ID: 10696945
Could you be more specific. If you need a pre written app it would help to know what your trying to listen for,
send back, what port to listen on etc...

I have several apps pre written and could modify one for you, I have a basic www server, an tftp server, etc... all use
multi winsock.

Jason HOlland

Author Comment

ID: 10697258
Hi Jason,

     Matter of fact, I need the sample source code! I need to write an app which will listen a port (not defined yet), i.e. port 1000, and will run a handshake (like login and password) with another application (client application). How does it work?
     The server code will receive a connection request (in fact several clients requests, from several places, different IPs)
     Server will ask for a predefined string. Depending on what the client application reads from the smartcard.
     Client will send this string
     String will be treated into the thread (that is reason I need threaded winsock), accessing a database (using ADO - mySQL) and passing data into the socket.
     Server will send the information to the client. At this point, server may ask for some infos and client will send msg back. Requesting more infos or giving acknowleges for messages sent.
     At the end, client doing the job (client code is already done, it is really simple), will close the connection or we can set to live the connection open for XX seconds, where we can have a timeout event (client)

    Is it more clear? If not, point the items that I need to clarify... If you understand, I need a multithread source code which each thread has it own winsock, able to treat data received/sent from/to its load winsock.

    Jason, thanks for your prompt answer!

Helton Ferreira

Expert Comment

ID: 10697503
Well, I am not sure if this is going to help you.
But here is some generic code for accepting connections, and creating dynamic winsocks.

Just create a form called frmmain, and a winsock called wsHTTP.
Just 1. It will create more for you.

You can rename the winsock later, and the form. But this code will show you how to do it.

if any thing confuses you just let me know.

Private Sub wsHTTP_Close(Index As Integer)
' Close Here
Debug.Print "Close"
End Sub

Private Sub wsHTTP_Connect(Index As Integer)
' Connect Here
Debug.Print "Connect"
End Sub

Private Sub wsHTTP_ConnectionRequest(Index As Integer, ByVal requestID As Long)
' Connect Request Here
Debug.Print "Connection Request"

    '// Create a New Connection
    Dim i As Integer
    i = wsHTTP.UBound + 1
    Load wsHTTP(i)
    wsHTTP(i).Accept requestID
    Debug.Print wsHTTP(i).RemoteHost
    Debug.Print wsHTTP(i).RemoteHostIP
    Debug.Print wsHTTP(i).RemotePort
End Sub

Private Sub wsHTTP_DataArrival(Index As Integer, ByVal bytesTotal As Long)
' Data Arrived! Do Something!!!
Debug.Print "Data Arrival"
Dim str, strSend As Variant
Dim s, e As Integer
Dim strPage As String

wsHTTP(Index).GetData str, vbString
Debug.Print CStr(Index)
Debug.Print str

    frmMain.wsHTTP(Index).SendData getPage(str)

End Sub

Private Sub wsHTTP_Error(Index As Integer, ByVal Number As Integer, Description As String, ByVal Scode As Long, ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)
' Errors Here
Debug.Print "Error"
Debug.Print Index & vbCrLf & Number & vbCrLf & Description & vbCrLf & Scode & vbCrLf & Source
End Sub

Private Sub wsHTTP_SendComplete(Index As Integer)
' Im all done, Im going to sleep now
Debug.Print "Send Complete"
End Sub

Private Sub wsHTTP_SendProgress(Index As Integer, ByVal bytesSent As Long, ByVal bytesRemaining As Long)
' Hang on, Im sending something
Debug.Print "Send In Progress"
End Sub

Get quick recovery of individual SharePoint items

Free tool – Veeam Explorer for Microsoft SharePoint, enables fast, easy restores of SharePoint sites, documents, libraries and lists — all with no agents to manage and no additional licenses to buy.


Author Comment

ID: 10697566

      It's a normal winsock server! It is not multithread?

      Let's see your sugestion:

20 connections arrives.
Winsock receives the first connection and execute a function fcnJobTime() which may take 20 seconds, which is time to complete execute the function. On this way, connection 1 will be treated, after connection 2,... and so on!

      What I want to do:

20 connections arrives:
20 connections will execute 20 threads with function fcnJobTime at the same time. For this, I believe to need the object Winsock and function fcnJobTime for each thread. And this sample code that I need to have!

Accepted Solution

jasonholland earned 2000 total points
ID: 10697610
I understand the multithreaded portion that you are speaking about, however you can not have more than 1 winsock
listening to 1 port at a time. It wont work. Multi thread or not. However the above code will allow you to have multiple
connections with multiple winsocks, all working in parrallel (like multi thread).

The winsocks will be seperate from each other, so they will be communicating to the clients seperately. And teh fncJobTime will
be executing in parrallel. Give it a try. You might have misunderstood when I said only put 1 winsock on the form.

The code will dynamically create more winsocks (hence more threads) as needed. You only have to physically put 1 on the form.
Look in the connection_request sub and you will see the "Load Winsock(i)". This is creating a new winsock.

I hope I answered your question. If not I will be up for a while, and I will answer again this evening.

Jason Holland
LVL 13

Expert Comment

ID: 10702607
Search www.pscode.com for MThread project

Author Comment

ID: 10702847

    There is something amazing. I'm not an IP expert, so it may sound basic. In my computer I have the following configuration this time (it's ADSL and IP changes at each connection):
Ethernet adapter Local Area Connection:
        Connection-specific DNS Suffix  . :
        IP Address. . . . . . . . . . . . . . :
        Subnet Mask . . . . . . . . . . . . :
        Default Gateway . . . . . . . . . .:
PPP adapter Globo.com:
        Connection-specific DNS Suffix  . :
        IP Address. . . . . . . . . . . . . . . .:
        Subnet Mask . . . . . . . . . . . . . .:
        Default Gateway . . . . . . . . . . . :

But the client software connects with IP and the server shows as LocalIP: Well, could you explain me why is it working like this? If my connection is from another computer, like yours; do I have to do any other code? Does it have to calculate mask, gateway,... do you know how to do that?

Thanks! Those 500 points are yours...


Expert Comment

ID: 10705454
I wouln't call myself an IP expert, but I am a network engineer. So I might be able to answer some of your questions to completion.

Could you please describe your network in more detail? Just the computers and how they are connected.

Here is an example of what I mean.

I have two computers both have windows 2000 operating system. They are connected through a switch with ethernet cables (or wireless network). Both computers use IP for the networking protocol.

Jason Holland

Author Comment

ID: 10705743
Hi Jason,

    Ok! Several computers, more than 50 with different operational systems (Windows 2000, XP,...) they will try to connect to the computer who has my server application. They all will have my client application.
My server application is into a LAN. This LAN has a server and my computer is connected to this server. My wish here is that you, any place you are, with a internet connection, can access my computer through specified port (i.e. port 1000), is it possible?

Expert Comment

ID: 10705787
Certainly is possible.

You can use a DNS name instead of an IP address. Like "MyServer.Globo.com", and set the .RemoteHost property on the winsock
instead of the IP address for the clients. This way it won't matter if the computer is on the LAN or on the Internet, it will get to the server.

Do you have a DNS server at your Disposal?

Author Comment

ID: 10705902
No! I don't have DNS server... Is that a problem if I set IP address?

Expert Comment

ID: 10709838
No not at all, your problem will arrise for clients inside the LAN and clients on the Internet.

The clients on the inside of the LAN will need to use the 10.1.1.x nunber, and the clients on the internet
will need to use the 200.171.244.x number.

If you can deal with those logistics your are fine. Just have the program check the clients IP before trying to connect,
if the clients winsock has an .LocalIP of 10.1.1.x then use the servers address in the LAN, if not then have it use the
IP outside on the internet.

Jason HOlland

Featured Post

Free recovery tool for Microsoft Active Directory

Veeam Explorer for Microsoft Active Directory provides fast and reliable object-level recovery for Active Directory from a single-pass, agentless backup or storage snapshot — without the need to restore an entire virtual machine or use third-party tools.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…
Suggested Courses
Course of the Month14 days, 1 hour left to enroll

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question