secf00tprint
secf00tprint

Reputation: 693

Blocking of access in Socket programming

I've implemented a simple echo server with C++ and g++

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

const int PORT_NUM = 10000;

int echo_server()
{
  const int BUFSIZE = 10;
  struct sockaddr_in addr, cli_addr;
  bzero((char *) &addr, sizeof(addr));
  bzero((char *) &cli_addr, sizeof(cli_addr));
  socklen_t addr_len;
  char buf[BUFSIZE];
  int n_handle;

  int s_handle = socket (AF_INET, SOCK_STREAM, 0);
  if (s_handle == -1) return -1;

  // Set up the address information where the server listens
  addr.sin_family = AF_INET;
  addr.sin_port = htons(PORT_NUM);
  addr.sin_addr.s_addr = INADDR_ANY;

  if (bind(s_handle, (struct sockaddr *) &addr, sizeof(addr))== -1)
  {
   return -1;
  }

  if (listen(s_handle,SOMAXCONN) == -1)
  {
   return -1;
  }

  addr_len = sizeof(cli_addr);
  n_handle = accept(s_handle, (struct sockaddr *) &cli_addr, &addr_len);
  if (n_handle != -1)
  {
   int n;
   int m = 0;
   int c = 0;
     while ((n = read(n_handle, buf, sizeof buf )) > 0)
     {
       while (m < n)
         {
           c = write(n_handle, buf, n);
           cout << buf << "-" << c;
           m += c;
         }
     }
     close(n_handle);
   }

  return 0;
}


int main()
{
 cout << "TestServer";
 return echo_server();
}

When I start the application the cout in main is suppressed, because of the accept statement in the echo server function. Only after I send some text and the function terminates, the program is prompting the cout in the main.

Why is that? Does it have something to do with the blocking behavior of the access function?

Upvotes: 0

Views: 143

Answers (1)

I suggest flushing the output, like

cout << buf << "-" << c << endl;

or

cout << "TestServer" << flush;

Upvotes: 2

Related Questions