开发者

Avoiding connection refused error for multiple sockets in C

开发者 https://www.devze.com 2023-03-29 07:19 出处:网络
Just a quick background. I am willing to open two sockets per thread of the application.The main thread has the accept() call to accept a TCP connection. There are three other threads and all of them

Just a quick background. I am willing to open two sockets per thread of the application.The main thread has the accept() call to accept a TCP connection. There are three other threads and all of them also have an accept(). The problem is sometimes in multithreaded environment, the client tries to connect before the accept call of the server in a child thread which results in "connection refused" error. The client doesn't know when the server is ready to connect I do 开发者_C百科not want the main thread socket to be sending any control information to the client like "You can now connect to the server". To avoid this, I have two approaches in my mind 1. To set a max counter(attempt) at the client side to connect to the server before exiting with connection refused error. 2. A separate thread whose only function is to accept connections at server side as a common accept function for all the thread connections except for the main thread.

Would really appreciate to know if there is any other approach. Thanks


Connection refused is not because you're calling accept late, it's because you're calling listen late. Make sure you call listen before any connect calls (you can check with strace). This probably requires that you listen before you spawn any children.

After you call listen on a socket incoming connections will queue until you call accept. At some point the not-yet-accepted connections can get dropped but this shouldn't occur with only 2 or 3 sockets.

If this is unix you can just use pipe2 or socketpair to create a pair of connected pipes/unix domain sockets with a lot less code. Of course, you need to do this before spawning the child thread and pass one end to the child.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号