I want a server program which should accept only maximum of one connection and it should discard other connections. How can I achieve this?
问题:
回答1:
Only accept()
a single connection.
Here is a typical server routine:
s = socket(...);
bind(s, ...);
listen(s, backlog);
while (-1 != (t = accept(s, ...))) {
// t is a new peer, maybe you push it into an array
// or pass it off to some other part of the program
}
Every completed accept()
call, returns the file descriptor for a new connection. If you only wish to receive a single connection, only accept()
once. Presumably you're done listening after this, so close your server too:
s = socket(...);
bind(s, ...);
listen(s, backlog);
t = accept(s, ...);
close(s);
// do stuff with t
If you wish to only handle a single connection at a time, and after that connection closes, resume listening, then perform the accept()
loop above, and do accept further connections until t
has closed.
回答2:
Corrections see underneath:
You can define the amount of accepted requests in the listen method.
listen(socketDescription, numberOfConnectionsPending);
Second parameter is for setting the number of pending connections and not the amount of connections itself..
If you set the numberOfConnections to 1 all the other clients which sends a request to the server will receive a timeout error..
Here you can find more informations: http://shoe.bocks.com/net/#listen
I read the listen documentation wrong. You should work with the accept method which is described in Matt's answer.
回答3:
Do you want to reject all connection or to make a queue? I think that what you are looking for is the so-called "singleton". Look at the wikipadia for the Singleton design pattern.