C在插座上打开第二个连接

时间:2017-12-05 02:07:41

标签: c sockets

我需要使用P2P编写分布式哈希表。从客户端获取请求的对等方需要具有开放连接以发回响应,并且还需要打开与其前任的连接以接收信息。我尝试在同一个套接字上第二次使用accept,但它没有用。

我读了一些关于分叉的解决方案,但我不确定它是否适合我的需要。 (而且我不确定如何在这里正确实现它)

我的基本设置:

memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = AI_PASSIVE;

  if ((gai_status = getaddrinfo(NULL, port, &hints, &md_srvinfo)) != 0) {
    fprintf(stderr, "error: %s\n", gai_strerror(gai_status));
    exit(gai_status);
  }

  int md_listen_socket = socket(md_srvinfo->ai_family, md_srvinfo->ai_socktype, md_srvinfo->ai_protocol);
  int yes;
  setsockopt(md_listen_socket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(1));
  bind(md_listen_socket, md_srvinfo->ai_addr, md_srvinfo->ai_addrlen);
  listen(md_listen_socket, 2);

while(1) {

    // accept connection
    struct sockaddr_storage client_address;
    socklen_t addr_size = sizeof(client_address);

    int md_active_socket;
    md_active_socket = accept(md_listen_socket, (struct sockaddr *) &client_address, &addr_size);
.
.
.
.
    recv(stuff from predecessor peer)
    send(stuff to md_active_socket)
}

编辑:

struct addrinfo *pred_srvinfo;
getaddrinfo(NULL, pred_port, &hints, &pred_srvinfo);
int pred_listen_socket = socket(pred_srvinfo->ai_family, pred_srvinfo->ai_socktype, pred_srvinfo->ai_protocol);

struct sockaddr_storage pred_address;
socklen_t pred_addr_size = sizeof(pred_address);
int pred_active_socket = accept(pred_listen_socket, (struct sockaddr *) &pred_address, &pred_addr_size);
connect(pred_active_socket, pred_srvinfo->ai_addr, pred_srvinfo->ai_addrlen);

有人能引导我走上正确的道路吗?

0 个答案:

没有答案