Archived Forum Post

Index of archived forum posts


How will multiple connections connect to this port at the same time?

Sep 19 '16 at 08:43

a bit confused here...
Please let me know, how to manage the following:
There is only one IP port, it is 8999, there will we on listener on this port.
How will multiple connections connect to this port at the same time?
Where are the threads handle, and where are the threads' execute procedure?
I mean the listener have to open separate threads for each connection and executes its own code...


If you peel away all the layers of code and are able to get to the heart of the matter, i.e. the actual system-level socket calls, you'll find that there is no such thing as accepting connections in parallel. At the heart of it is this:

The "listen" system call (and it doesn't matter whether it's Windows, Linux, MacOSX, etc.) has an argument for a "backlog"

The backlog argument defines the maximum length to which the queue of pending connections for sockfd may grow. If a connection request arrives when the queue is full, the client may receive an error with an indication of ECONNREFUSED or, if the underlying protocol supports retransmission, the request may be ignored so that a later reattempt at connection succeeds.

With Chilkat, you'll have a thread of your own whose sole job is to accept incoming connections and hand of the connected socket to some other thread in your program that will read/write the connected socket. Your thread for receiving connections should do only that -- receive (accept) a connection, and quickly give it to another thread for processing, and then get back to receiving the next connection.

I can't give you an example of the application infrastructure you might design for your threading. The way to accept a connection is shown here:

The call to BindAndListen would be placed just before the loop. Your program would have a loop that calls AcceptNextConnection, hands the connected socket to something else (another thread) that owns and manages the connection, and then returns to the start of the loop to accept the next connection. The AcceptNextConnection loop should be in a background thread.