how to restrict number of connections in client server program

北战南征 提交于 2019-12-11 07:12:43

问题


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.



来源:https://stackoverflow.com/questions/4164575/how-to-restrict-number-of-connections-in-client-server-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!