如何限制客户端服务器程序的连接数

发布于 2024-10-02 20:01:09 字数 54 浏览 3 评论 0原文

我想要一个服务器程序,它应该只接受最多一个连接,并且应该丢弃其他连接。我怎样才能实现这个目标?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

静水深流 2024-10-09 20:01:09

accept() 单个连接。

这是一个典型的服务器例程:

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
}

每个完成的 accept()调用,返回新连接的文件描述符。如果您只想接收单个连接,则只需accept()一次。想必您在此之后已经完成侦听,因此也关闭您的服务器:

s = socket(...);
bind(s, ...);
listen(s, backlog);
t = accept(s, ...);
close(s);
// do stuff with t

如果您希望一次只处理一个连接,并且在该连接关闭后,恢复侦听,然后执行 accept()循环上面的内容,并接受进一步的连接,直到 t 关闭。

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.

眼角的笑意。 2024-10-09 20:01:09

更正见下文:
您可以在listen方法中定义接受的请求数量。

listen(socketDescription, numberOfConnectionsPending); 

第二个参数用于设置待处理连接的数量,而不是连接本身的数量。< /em>

如果将 numberOfConnections 设置为 1,则向服务器发送请求的所有其他客户端都将收到超时错误..

这里您可以找到更多信息:http://shoe.bocks.com/net/#listen

我读错了监听文档。您应该使用马特的答案中描述的接受方法。

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.

秋风の叶未落 2024-10-09 20:01:09

您想拒绝所有连接还是建立一个队列?
我认为你正在寻找的是所谓的“单例”。
查看 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文