Does listen() run continuously or do I need to loop it to keep receiving connections on a socket?

StackOverflow https://stackoverflow.com/questions/23068717

  •  03-07-2023
  •  | 
  •  

質問

I'm running a client and server on the same machine using a loopback address for learning purposes yet my "server" code seems to fly back listen() and then hangs on my connect(). Does listen() need to be in an endless loop to keep receiving connections?

How would I determine a connection is made/in the queue if listen() returns 0 even when I haven't made a connection yet?

I have an accept() call following but the code hangs on that spot. I have debug statements right before and after and it never gets past the accept().

On the other end my client code seems to connect() just fine (doesn't throw an error) and appears to write and complete even though the server code never gets the connection.

役に立ちましたか?

解決

The listen function defines the backlog. Only need to call this once.

Then use accept to receive an incoming connection. Best to deal with this promptly and go around again for another accept.

他のヒント

Both connect() and accept() should block while waiting for a connection.

   connect()  #client blocks while waiting for remote server to answer
   accept()   #server blocks while waiting for a client

listen() should not block at all. It tells the OS to allocate additional memory for requests, so that the OS can queue clients who arrive at the same time. You only need to call it once.

If accept() never completes in the server, then you most likely never have a connection. If the connect() call is completing in your client, then you need to check its return value. If it returns with a -1, then the connection failed. It sounds like this is most likely what is happening. You can still write to a socket without a connection, but your message will not go anywhere.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top