如何限制客户端服务器程序的连接数
我想要一个服务器程序,它应该只接受最多一个连接,并且应该丢弃其他连接。我怎样才能实现这个目标?
I want a server program which should accept only maximum of one connection and it should discard other connections. How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅
accept()
单个连接。这是一个典型的服务器例程:
每个完成的
accept()
调用,返回新连接的文件描述符。如果您只想接收单个连接,则只需accept()
一次。想必您在此之后已经完成侦听,因此也关闭您的服务器:如果您希望一次只处理一个连接,并且在该连接关闭后,恢复侦听,然后执行
accept()
循环上面的内容,并接受进一步的连接,直到 t 关闭。Only
accept()
a single connection.Here is a typical server routine:
Every completed
accept()
call, returns the file descriptor for a new connection. If you only wish to receive a single connection, onlyaccept()
once. Presumably you're done listening after this, so close your server too: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 untilt
has closed.更正见下文:
您可以在listen方法中定义接受的请求数量。第二个参数用于设置待处理连接的数量,而不是连接本身的数量。< /em>
如果将 numberOfConnections 设置为 1,则向服务器发送请求的所有其他客户端都将收到超时错误..这里您可以找到更多信息:http://shoe.bocks.com/net/#listen
我读错了监听文档。您应该使用马特的答案中描述的接受方法。
Corrections see underneath:
You can define the amount of accepted requests in the listen method.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.
您想拒绝所有连接还是建立一个队列?
我认为你正在寻找的是所谓的“单例”。
查看 wikipadia 的 Singleton 设计模式。
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.