Hello, I am having a problem with sockets. Not the sockets themselves, exactly, but more of the recieving and accepting of messages and connections (respectively) at the same time.

My program runs a loop where it will wait to accept a connection (using accept()), and then wait to recieve a message (using recv()). Then it loops again and waits for a connection. The problem, obviously, being that if a client wants to send a message, the server will be waiting to accept a connection rather than to recieve a message.

Were I, however, to make it accept the connection and then loop only the recieving of messages, then other clients could not successfully connect.

So I would need to do one of the following:
1) Wait for both a recv() and accept() at the same time (I think it's called multithreading, but I have no idea how to do it).
2) Be able to find out when accept() will be necessary, and otherwise loop recv() functions. This way would require the recv() function to be done often, so that it would have a chance to find out that it needs to run accept().
3) Tell the accept() and recv() statement that they can only wait for a certain amount of time before giving up. Or something to that effect.


I am sorry if this problem is stupid; I don't know sockets very well. Also, the above possible solutions may all be impossible, but they are just three things that could help if they could be done.

Here is the source code of the server loop (please assume that the rest works correctly):

while(true){ 
	bl = listen(s, 10);
	if(bl){
		cout << "Listen error.";
		system("pause");
		return -1;
	}
	ac = accept(s, NULL, NULL);
	if(ac == INVALID_SOCKET){
		cout << "Accept error.";
		system("pause");
		return -1;
	}
	sr = recv(ac, buffer, 255, 0);
	if(sr == -1){
		cout << "Recv error.";
		system("pause");
		return -1;
	}
	cout << "Message recieved: " << buffer << "\n";
}

No, your question is not stupid. If is one that occurs to all beginners in socket programming. Actually all 3 of your options are possible. So I will give you the answer for the first question which is I think the easiest and good to get some exposure to thread programming.

1) Wait for both a recv() and accept() at the same time (I think it's called multithreading, but I have no idea how to do it).

You have the CreateThread or _beginthread which is much easier than the former. You can do the accepting operation one thread and the receiving in another one. I think the Linux equivalent is pthread_create
Once you get to know threads this is the easiest to handle.

Thank you for this information. I will try to learn _beingthread from the page you suggested.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.