Reputation: 8488
I have a linux server program that waits for incoming connections from a client and depending on what command you send it performs a different connection. Here is the pseudo-code
setup_socket();
while(1)
{
listen();
newfile_descriptor = accept();
int command
read(newfile_descriptor,&command,sizeof(int));
switch(command)
{
...
}
}
But when I want to send more than one command with the same client it listens forever (since a new connection is not being made). Is there a way to check if there is already connection before listening to a new one?
Upvotes: 1
Views: 5017
Reputation: 11
The very first thing... Is to move your listen() outside the while loop. :p
Upvotes: 1
Reputation: 84169
You either demultiplex the socket IO with select
/poll
, or have a separate thread read the commands on the client socket.
Upvotes: 2
Reputation: 359826
To elaborate on Nikolai's response, check out the indispensable Beej's guides. It is a very standard practice to spawn a new thread immediately after calling accept() inside of your while(1) loop; this thread handles all the communication with the client so that the main thread can continue listen()ing for new incoming connections and accept()ing when they arrive.
Here is the specific section on select(), which I know about, but haven't actually used before.
Upvotes: 1
Reputation: 4425
What you need is some basic protocol which allows the client to inform you that it is done sending commands. It could be as simple as the client continues to send commands, then closes the socket when it no longer needs to send any more. In that case, you would simply continue to read from the socket until it is closed. In your pseudo code, it would look something like this:
setup_socket();
while(1) {
listen();
newfile_descriptor = accept();
int command;
do {
command = read(newfile_descriptor,&command,sizeof(int));
if (command > 0) {
switch(command) {
...
}
}
} while (command > 0);
}
Upvotes: 1
Reputation: 12695
How about a loop where you read the commands:
setup_socket();
while(1)
{
listen();
newfile_descriptor = accept();
int command
command = read(newfile_descriptor,&command,sizeof(int));
while(command) {
switch(command)
{
...
}
// get next command, or figure out closed connection
command = read(newfile_descriptor,&command,sizeof(int));
}
}
Upvotes: 2
Reputation: 45365
How about checking if you can read from the socket some more? I would think you should close your connection at the end of the command if there isn't anything more coming in.
Upvotes: 1