Here is my code:
void error(const char *msg)
{
perror(msg);
exit(1);
}
void sServer::acceptClientConnections(int listenerSocket)
{
struct sockaddr clientAddress;
socklen_t sizeOfClientAddress = sizeof(clientAddress);
while (true)
{
int newConnection = accept(listenerSocket, &clientAddress, &sizeOfClientAddress);
std::cout << "Someone connected ... " <<std::endl;
liveConnections.push_back(newConnection);
}
}
int sServer::getServerListenerSocket()
{
return serverListenerSocket;
}
sServer::sServer(int port)
{
int serverListenerSocket;
struct sockaddr_in serv_addr;
serverListenerSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverListenerSocket < 0)
error("ERROR opening a socket. Cannot start sever. Exiting ...");
memset((char *) &serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port);
std::cout << "Host ip: " << serv_addr.sin_addr.s_addr << "\n";
if ( bind(serverListenerSocket, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0 )
error("ERROR on binding server socket. Are you running another instance of this server ?");
listen(serverListenerSocket, 45);
}
Called like this:
int main()
{
sServer superServer(9889);
std::thread handleConnections( &sServer::acceptClientConnections, superServer, superServer.getServerListenerSocket() );
}
I was expecting accept to wait for incoming connections, and when a connection comes in, become active.
But instead, when i run the program, it continuously prints "Someone connected ..." even though no connections are being made.
Ironically, if I start the thread at the end of the constructor, it works well.
Can you please explain why this is happening and what would be the correct way to accept a connection ?