传输结束已连接错误:106与connect()

时间:2018-03-20 07:05:05

标签: c sockets unix ipc

我已经开始使用SOCK_STREAM类型的UNIX域套接字实现服务器 - 客户端模型。

提前致谢

1 个答案:

答案 0 :(得分:0)

如果您的套接字已经连接,您需要避免再次连接,您可以在客户端代码中保留一些标志,表明您的客户端套接字已经连接,基于该跳过再次连接。

我已经在下面编辑了你的服务器代码,以显示我想在评论中说的内容(你需要将已接受的fd放入选择的阅读集中,以便你可以检查任何客户发布的任何数据,你也有多个客户端连接到你所以你必须在数组中保持接受的套接字):

int cltfdlen = 0;
int cltfds[FD_SETSIZE];
int maxFD = sockfd;
  int sun_path_size = sizeof(client_address.sun_path);
  client_address.sun_family = AF_UNIX;
  strncpy(client_address.sun_path, SOCKET_NAME, sun_path_size);
  client_len = sizeof(client_address);

  cli_interval.tv_sec = 60;
  cli_interval.tv_usec = 0;

while (1) {

   FD_ZERO(&read_fds);
   FD_SET(sockfd, &read_fds);
   for(i=0;i<cltfdlen;cltfdlen++)
    FD_SET(cltfds[i], &read_fds);
   int activity = select(maxFD + 1, &read_fds, NULL, NULL, &cli_interval);

   if ((activity < 0) && (errno !=EINTR)) {
     printf("socket select failed errno %d\n", errno);
     return 1;
   }

if (FD_ISSET(sockfd, &read_fds)) {
    cli_sockfd = accept(sockfd,
            (struct sockaddr *)&client_address,
            &client_len);
    if(cli_sockfd < 0) {
        printf("accept from IPC socket failed");
        return 1;
    }
    else
    {
        cltfds[cltfdlen++] = cli_sockfd;
        if(maxFD < cli_sockfd)
           maxFD = cli_sockfd 
        continue;
    }
}
    msg = (msg_t *) malloc(sizeof(msg_t));
    if (msg == NULL) {
        printf("Memory allocation failed for msg");
        close(ipc_sockfd);
        ipc_sockfd = -1;
        return 1;
    }

    memset(msg, 0, sizeof(msg));
    for(i=0;i<cltfdlen;i++)
    {
    if(FD_ISSET(cltfds[i], &read_fds))
    {
        if (read(cltfds[i], (void *)msg, sizeof(msg_t)) == -1) {
            printf("Read from IPC socket failed");
            return 1;
        }
    }
    }

    close(cli_sockfd);
    cli_sockfd = -1;

}