Click here to Skip to main content
15,881,424 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

This loop runs indefinitely on a separate std::thread unless I set listening to true. The problem is, I can't terminate the loop if the user decides to shutdown the server because accept blocks the thread until a connection is established. Is there a better approach than to use TerminateThread?

while (_this->listening)
{
    SOCKET client;
    sockaddr_in from;
    int fromlen = sizeof(from);

    client = accept(*server_socket, (sockaddr*)&from, &fromlen);
    printf("Client connected\r\n");

}


What I have tried:

---------------------------------------------------------
Posted
Updated 17-Jul-18 1:47am
v2
Comments
11917640 Member 17-Jul-18 3:00am    
You need to close server_socket from another thread, in this case accept function returns immediately.
[no name] 17-Jul-18 6:29am    
Does that work even if accept() has already been called and is currently blocking, then server_socket is closed?
11917640 Member 17-Jul-18 6:57am    
Yes, it works in this case. After closing the socket accept should unblock and fail.
[no name] 17-Jul-18 6:58am    
Ok excellent, would you mind writing a solution so I can accept it please?
11917640 Member 17-Jul-18 7:48am    
Posted.

1 solution

You need to close server_socket from another thread, in this case accept function returns immediately. Note that accept function fails and doesn't return valid socket handle, if listening socket is closed, so you need to exit the loop when this happens.
 
Share this answer
 
v2
Comments
[no name] 17-Jul-18 8:06am    
Thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900