I'm writing a client-server pair in C++ using Linux sockets. I want the server to listen for a connection, and while one client is connected the server should reject any other clients that try to connect.
I tried implementing this by setting the backlog parameter in the listen function to 0 and to 1 and neither one of those values seems to work. The first client connects as expected, but any subsequent clients just block while the first client finishes. What's really confusing to me is that they don't block on connecting to the server, they block on the first read.
I used the code here to get started writing my client and server. Does anyone know what I need to change to get the server to accept only one client connection, and drop any subsequent connection attempts?
1 Answer. At any time between two particular end hosts, only one TCP connection can be there between any two ports. A TCP connection is uniquely identified by 5 pieces of information in the TCP and IP headers.
On the TCP level the tuple (source ip, source port, destination ip, destination port) must be unique for each simultaneous connection. That means a single client cannot open more than 65535 simultaneous connections to a single server. But a server can (theoretically) serve 65535 simultaneous connections per client.
Irrespective of stateful or stateless protocols, two clients can connect to same server port because for each client we can assign a different socket (as client IP will definitely differ). Same client can also have two sockets connecting to same server port - since such sockets differ by SRC-PORT .
When you accept a connection, a new socket gets created. The old one is still used to listen for future connections.
Since you want to only allow 1 connection at a time, you could just accept the connections, and then close the new accepted socket if you detect you are already processing another.
Is there a net difference that you are looking for compared to closing the new accepted socket right after the accept? The client will know as soon as it tries to use its socket (or right away if it is already waiting on the server with a read call) with a last error of: server actively closed the connection.
Just don't fork()
after accept()
.
This pseudo-C-code will only accept one client at once.
while(1) {
listen()
accept()
*do something with the connection*
close()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With