tags:

views:

1084

answers:

5

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?

+1  A: 

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.

Matt Price
+2  A: 

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));
  }
}
caskey
+1  A: 

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);
}
IRBMe
+2  A: 

You either demultiplex the socket IO with select/poll, or have a separate thread read the commands on the client socket.

Nikolai N Fetissov
+1  A: 

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.

Matt Ball