I'm writing an app that involves a listening loop that listens for and accepts new connections when the user clicks a menu item in the GUI. here is my listening function, which works fine like this:
when the "Start Listening" menu item is clicked it assigns TRUE to bListen, and calls this function. the message box is displayed, when I hit "OK" it is displayed again, and repeats until the "Stop Listening" menu item is clicked (which assigns FALSE to bListen).Code:int Listen(void) { while(bListen) MessageBox(NULL, "test", "test", MB_OK); return 0; }
now, here it is with a little bit of socket code added.
ignore the MessageBox()s, I just added them for debugging purposes. when it looks like this and I hit "Start Listening", the program hangs, which I assume is because the code in the loop is executing too quickly, resulting in some major CPU usage. I tried adding a Sleep(30000) in the loops block (outside of all if else blocks), however it doesn't seem to help.Code:int Listen(void) { WSADATA wsad; SOCKET lsock, csock; SOCKADDR_IN sin; int err; /* Initiate WinSock 2.2, and create and bind a socket for listening. */ WSAStartup(0x202, &wsad); if((lsock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == SOCKET_ERROR) { err = WSAGetLastError(); WSACleanup(); return err; } sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(INADDR_ANY); sin.sin_port = htons(usPort); if(bind(lsock, (PSOCKADDR)&sin, sizeof(SOCKADDR_IN)) == SOCKET_ERROR) goto SockErr; /* Start listening and accepting new connections. */ listen(lsock, SOMAXCONN); while(bListen) { if((csock = accept(lsock, (PSOCKADDR)&sin, NULL)) != SOCKET_ERROR) { /* Here I plan to create a thread for each new connection. */ MessageBox(NULL, "hello", "hi", MB_OK); } else { SockErr: err = WSAGetLastError(); MessageBox(NULL, "error", "err", MB_OK); closesocket(lsock); WSACleanup(); return err; } } closesocket(lsock); WSACleanup(); return 0; }
is this the problem here, the loop is consuming alot of the CPU causing the program to hang? do you think creating a thread for this function would solve the problem? also if I created a thread for it, should I still add a Sleep() statement (as I believe it would just cause the threads execution to pause, not the entire program like it would if I added a Sleep() to it and called it normally like I had tried)?
any help here would be greatly appreciated. thank you in advance.![]()



LinkBack URL
About LinkBacks




. after reading the msdn description of accept() thoroughly I realized a few things I had wrong, first of all I was testing the return of accept() against SOCKET_ERROR, when I should have been testing it against INVALID_SOCKET. secondly, with this test I noticed that the message box never appeared (I expected accept() to return INVALID_SOCKET when there was no connection to accept), meaning accept() was not returning any value immediately.