Problem on winsock connection

Posted on 2001-07-03
Last Modified: 2013-11-13
I'm using winsock component (tcpip) for communication between pc to pc. One end as winsock client and other end as winsock server. Everything find, i can connect, send/receive data and close connection.

Problem arise when, multiple winsock client try to connect to winsock server. Only one client can connect at one time.

How to make multiple connection possible?
Question by:azsoft
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
  • +6

Expert Comment

ID: 6249550
i just solved this same problem about 2 weeks ago.

it's easy.

create your WSock object, and set the Index value to 0 (zero) (this creates a Control Array)

in your code:

Private Sub Form_Load()
  wsock(0).localPort=80 'or whatever port you want
End Sub

'this will allow multiple connections
Private Sub WSock_ConnectionRequest(Index as Integer, RequestID as Integer)

'make sure that wsock 0 is listening
if index=0 then
  dim counter as integer
  counter = wsock.ubound+1
  load WSock(counter)
end if

from now on, in any of your event codes, you will have the Index value to use. just make sure you always specify the index when using the WSock object.

WSock(Index).sendata "hello"

etc. etc.

Expert Comment

ID: 6249555
if you post your email address, I'll send you over an actual VB6 source code that does all this.

Author Comment

ID: 6249603
The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.


Expert Comment

ID: 6249681
Just wondered:
Why use the 0-index control to listen to the port?
Why not use one control to listen to the port and another with a object array to handle all connections ??
Wouldn't that give some more controlable code?

First bug i saw i the code printed was that the winsock-control never was unloaded!
Let's say we made a nice little http-server out of this.
It runs without a problem in, let's say, a week.
Imaging the number of winsock-controls which is loaded into the memory by now.
Anyway, it's pretty easy to solve this.
Just unload the control then connection closes and then you a new control, loop throw the object array and reload the first one missing.

Expert Comment

ID: 6249703
I just sent it.

Expert Comment

ID: 6249712

by using the 0 index, you save on memory and other cpu resources.

that was just an example, of course i didn't close the winsock. there's not even any code in there to do anything aside from verify that you actually made a connection.


load the Host onto your computer and run it, then goto a couple of other computers and load the Client, and have the clients connect to the host at the same time.
LVL 16

Accepted Solution

Richie_Simonetti earned 100 total points
ID: 6249823
I can't post the url here (Later i will do). It is from Planet source code i think.
This is a complete form:

Object = "{248DD890-BB45-11CF-9ABC-0080C7E7B78D}#1.0#0"; "MSWINSCK.OCX"
Begin VB.Form Form1
   AutoRedraw      =   -1  'True
   Caption         =   "Form1"
   ClientHeight    =   3195
   ClientLeft      =   60
   ClientTop       =   345
   ClientWidth     =   4680
   LinkTopic       =   "Form1"
   ScaleHeight     =   3195
   ScaleWidth      =   4680
   StartUpPosition =   3  'Windows-Standard
   Begin VB.Timer Timer1
      Interval        =   200
      Left            =   1560
      Top             =   1440
   Begin MSWinsockLib.Winsock Winsock1
      Index           =   0
      Left            =   2160
      Top             =   1440
      _ExtentX        =   741
      _ExtentY        =   741
      _Version        =   393216
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Dim i As Long
Dim Con As Long

Private Sub Form_Load()
i = 0
Con = 0
Winsock1(0).LocalPort = 80
End Sub

Private Sub Timer1_Timer()
Me.Caption = "Verbindungen: " & Con
End Sub

Private Sub Winsock1_Close(Index As Integer)
If Index = 0 Then
End If
Con = Con - 1
End Sub

Private Sub Winsock1_ConnectionRequest(Index As Integer, ByVal requestID As Long)
If Index = 0 Then
i = i + 1
Con = Con + 1
Load Winsock1(i)
Winsock1(i).LocalPort = 0
Winsock1(i).Accept requestID
End If
End Sub

Private Sub Winsock1_DataArrival(Index As Integer, ByVal bytesTotal As Long)
Winsock1(Index).GetData newData$
End Sub

Private Sub Winsock1_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)
Con = Con - 1
End Sub

Expert Comment

ID: 6252931
I've done this myself a couple of times...

I've always done what Wippie is talking about.

Have one control: wskListen that receives ONLY connection requests.  Once a machine requests a connection I create a new control from a wskConnection Control Array.  This is where all future communication occurs.

To save on resources, when a user disconnects, I have a string that holds the comma-seperated indices of available controls.  This way I can see if there's an available unused control so I don't have to create another.

There is ONE thing that hasn't been mentioned yet.  All of this should work, IN THEORY.  But there's a problem with the control.  If you try to send out information over all of the controls you will find that it will not be received by everyone.  There's an easy way to resolve this.  A couple of well placed DoEvents will take care of it.

Here's an example:

(If playerID = 0 then a message is sent to all users, otherwise it's sent only to 1 player.  Note the use of DoEvents)

Public Sub SendMessage(strMessage As String, Optional _
                      playerID As Integer = 0, Optional _
                      newLine As Boolean = True)
    If newLine Then
        strMessage = strMessage & vbCrLf
    End If
    strMessage = vbCrLf & strMessage
    If playerID <> 0 Then
        If player(playerID).Status >= PLR_NAME Then
            frmMain.wskPlayer(playerID).SendData strMessage
        End If
        Dim i As Integer
        For i = 1 To frmMain.wskPlayer.UBound
            If player(i).Status >= PLR_NAME Then
                frmMain.wskPlayer(i).SendData strMessage
            End If
    End If

End Sub

Hope that helps!

Expert Comment

ID: 6252938
Oops...sorry Richie, just noticed you mentioned the DoEvents in your sourcecode first :)
LVL 16

Expert Comment

ID: 6252970
That's OK!
First, it is not my code.
Second, indentation, indentation, indentation,...!

Expert Comment

ID: 6253896
Just as an aside...

With at least some versions of the Winsock control, that component leaks memory when removed from a control array. There's an MSDN article about it somewhere. It may have been corrected in recent versions of the control, for all I know, but it is something to watch out for.

When I needed to do something with a dynamic number of winsock controls a while back, I created my app as an MDI app, put winsock controls on MDI child windows and loaded and unloaded those windows as required. With the unloading of the child window, all the resources of its controls are cleaned up, and the memory leak doesn't happen. It worked very well.

In that case, I had other reasons to use that structure, though. I didn't actually find out about the memory leak problem until later. When I did, I stopped and looked carefully at my program's structure, and determined that I had already sidestepped the problem.

Expert Comment

ID: 6979338
ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101, Netminder or Mindphaser will return to finalize these if they are still open in 7 days.  Experts, please post closing recommendations before that time.

Below are your open questions as of today.  Questions which have been inactive for 21 days or longer are considered to be abandoned and for those, your options are:
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you, but may help others. You must tell the participants why you wish to do this, and allow for Expert response.  This choice will include a refund to you, and will move this question to our PAQ (Previously Asked Question) database.  If you found information outside this question thread, please add it.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question (if it has no potential value for others).
   --> Post comments for expert of your intention to delete and why
   --> YOU CANNOT DELETE A QUESTION with comments; special handling by a Moderator is required.

For special handling needs, please post a zero point question in the link below and include the URL (question QID/link) that it regards with details.
Please click this link for Help Desk, Guidelines/Member Agreement and the Question/Answer process.

Click you Member Profile to view your question history and please keep them updated. If you are a KnowledgePro user, use the Power Search option to find them.  

Questions which are LOCKED with a Proposed Answer but do not help you, should be rejected with comments added.  When you grade the question less than an A, please comment as to why.  This helps all involved, as well as others who may access this item in the future.  PLEASE DO NOT AWARD POINTS TO ME.

To view your open questions, please click the following link(s) and keep them all current with updates.

To view your locked questions, please click the following link(s) and evaluate the proposed answer.

*****  E X P E R T S    P L E A S E  ******  Leave your closing recommendations.
If you are interested in the cleanup effort, please click this link 
POINTS FOR EXPERTS awaiting comments are listed in the link below
Moderators will finalize this question if in @7 days Asker has not responded.  This will be moved to the PAQ (Previously Asked Questions) at zero points, deleted or awarded.
Thanks everyone.
Moderator @ Experts Exchange
LVL 49

Expert Comment

ID: 7147983
Hi azsoft,
It appears that you have forgotten this question. I will ask Community Support to close it unless you finalize it within 7 days. I will ask a Community Support Moderator to:

    Accept Richie_Simonetti's comment(s) as an answer.

azsoft, if you think your question was not answered at all or if you need help, just post a new comment here; Community Support will help you.  DO NOT accept this comment as an answer.

EXPERTS: If you disagree with that recommendation, please post an explanatory comment.
DanRollins -- EE database cleanup volunteer

Expert Comment

ID: 7182112
Comment from expert accepted as answer

E-E Moderator

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Enums (shorthand for ‘enumerations’) are not often used by programmers but they can be quite valuable when they are.  What are they? An Enum is just a type of variable like a string or an Integer, but in this case one that you create that contains…
If you haven’t already, I encourage you to read the first article ( in my series to gain a basic foundation of R and R Studio.  You will also find the …
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

707 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