套接字编程中的访问阻塞

Blocking of access in Socket programming

本文关键字:访问 编程 套接字      更新时间:2023-10-16

我已经用c++和c++实现了一个简单的回显服务器

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

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

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

我建议冲洗输出,如

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

cout << "TestServer" << flush;