简体   繁体   English

检查套接字侦听backlog队列是否为空

[英]Check if socket listen backlog queue is empty

Is there any way to check if there are no pending connection requests to the server? 有没有办法检查服务器是否没有挂起的连接请求?

In my case, I have this code, from C: 就我而言,我有这个代码,来自C:

listen(mysocket, 3);
//while(no pending connections) do this
int consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);

And what I need, is that while there are no pending connections, do something else, instead of getting stuck waiting, by calling accept(). 而我需要的是,虽然没有待处理的连接,但是通过调用accept()来做其他事情,而不是等待等待。

You can set a socket in non-blocking mode with fcntl . 您可以使用fcntl在非阻塞模式下设置套接字。

fcntl(sockfd, F_SETFD, O_NONBLOCK);

After that, a call to accept(sockfd) will either immediately return a newly accepted connection or immediately fail with EWOULDBLOCK which you can use to decide to do “something else”. 之后,调用accept(sockfd)将立即返回一个新接受的连接,或者立即失败并使用EWOULDBLOCK ,您可以使用它来决定做“其他”。

Another option would be to use select , maybe with a finite timeout, to gain finer grained control over blocking. 另一种选择是使用select ,可能具有有限超时,以获得对阻塞的更精细控制。

You can spawn a new thread and do your alternate work in that thread while the main thread waits for clients. 您可以生成一个新线程,并在主线程等待客户端时在该线程中执行备用工作。 Once a client is connected, accept() gets unblocked and then you can cancel the newly spawned thread. 连接客户端后, accept()将被取消阻止,然后您可以取消新生成的线程。

The code should be on the lines of: 代码应该是:

while(1) {
    pthread_create(&thread, NULL, do_something_else, NULL);
    consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);
    pthread_cancel(thread);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM