1

I want to stop accepting connection from the main thread .. I have copied the original code here. in this server. it spawn a new thread per each connection. there is a seperate thread to clean the connection pool and another thread for user command processing all works perfectly. i just want to stop accepting new connection based on user commands. the accept method exists within the main thread i used the following logic to stop accepting

while (bListening && (sctCommSocket = accept(sctBaseSocket,(struct sockaddr *)&addrClient,&c)) != INVALID_SOCKET)

but after setting bListening to true.. the loop still accept 1 connection.. but this was not expected. please explain

user207421
  • 305,947
  • 44
  • 307
  • 483
Hara
  • 35
  • 4

2 Answers2

0

When you set the flag the loop was already blocked in accept(), so it accepted the next connection.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • I undersand the logical trap.. can you suggest a solution.. is there any pausing mechanism rather trying this way – Hara Nov 04 '16 at 07:31
  • 1
    If you want to stop accepting, close the listening socket. Nothing else will do because of the listen backlog queue. – user207421 Nov 04 '16 at 09:20
-1

This is very similar to the question asked here: Is it possible (and safe) to make an accepting socket non-blocking?

I think that will solve your problem too although it's not clear from the code snippet what operating system and multithreading library you are using.

Edit:

Here's a good guide on network programming: http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html

A section that addresses the blocking problem specifically is http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html#Blocking

There are multiple ways to address this issue and which is the "best" will depend on your specific case. As a commenter suggested, you will have to setup the socket to be non-blocking before you call accept the first time.

Community
  • 1
  • 1
Andrew
  • 518
  • 2
  • 9
  • The comments in your link clearly state that changing the blocking mode won't affect an `accept()` that is already in progress. – user207421 Nov 04 '16 at 23:46
  • @EJP Right; you have to set it up to be non-blocking before calling it. Then you have to write extra code around it to stop calling it once bListening is false. The link explains how to make accept() non-blocking so then the calling code can be modified to do what the asker wants. – Andrew Nov 05 '16 at 17:27