在Socket编程中阻止访问

时间:2011-11-21 18:47:45

标签: c++ sockets

我用C ++和g ++实现了一个简单的echo服务器

#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();
}

当我启动应用程序时,由于echo服务器函数中的accept语句,主要的cout被抑制。只有在我发送一些文本并且函数终止后,程序才会提示主要的cout。

为什么?它是否与访问函数的阻塞行为有关?

1 个答案:

答案 0 :(得分:2)

我建议刷新输出,例如

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

cout << "TestServer" << flush;