bhavesh
bhavesh

Reputation: 1406

Multiple TCP connections vs single connection

I am designing a Data Distributor (say generating random number) where it will serve multiple clients.

The client C first sends the list of numbers in which it is interested to DD over TCP and listens for data on UDP. After some time (few minutes) the client may renew its subscription list by sending more numbers to DD.

I can design this in 2 ways.

FIRST:

New_Client_Connected_Thread(int sock_fd)
{
    --Get Subscription
    --Add to UDP Publisher List
    --close(sock_fd)
}

Everytime client wants to subscribe to new set of data it will establish a new TCP connection.

SECOND:

New_Client_Connected_Thread(int sock_fd)
    {
        while(true)
        {
            --wait for new subscription list
            --Get subscription
            --Add to UDP Publisher List.

        }
    }

Here only 1 TCP connection per client would be required.

However if the client does not send new request, the Client_Thread would be waiting unnecessarily for long time.

Given that my Data Distributor would be serving lots of clients which of them seems to be the efficient way?

Upvotes: 0

Views: 963

Answers (1)

TheRoDent
TheRoDent

Reputation: 36

Libevent, or libev, which supports an event driven loop is probably more appropriate for the TCP portion of this.

You can avoid the threading, and have a single loop for the TCP portion to add your clients to the Publishers' list. Libevent is very efficient at managing lots and lots of connections and socket teardowns per second and is used by things like Tor (The onion router)

It seems like the TCP connection in your application is more of a "Control Plane" connection, and thus it's probably going to depend on how often your clients need to "control" your server thats going to make the decision whether to leave the socket open or close it after controlling. Keep in mind that keeping thousands of TCP connections open permanently does it kernel resource on the host, but on the other opening and closing connections the whole time introduces some latency due to the connection setup time.

See https://github.com/libevent/libevent/blob/master/sample/hello-world.c for an example of a libevent TCP server.

Since you're coding in C++, you will probably interested in the http://llucax.com.ar/proj/eventxx/ wrapper for libevent

Upvotes: 2

Related Questions