Unix套接字c

时间:2017-02-21 08:35:03

标签: c multithreading unix-socket

到目前为止,一切都运转良好。我遇到的问题就是我无法想到一种分配方式,或者我会说给连接到服务器的客户端命名,以便其他知道的客户端写了一条消息

服务器:

while (1) {
    FD_ZERO(&read_set);
    //FD_ZERO(&write_set);

    FD_SET(fd, &read_set);
    //FD_SET(fd, &write_set);

    for (i = 0; i < num_clients; i++) { //at first this part will not excute
        FD_SET(clients[i], &read_set);
    }

    select(fd + num_clients + 1, &read_set, NULL, NULL, NULL);


    if (FD_ISSET(fd, &read_set)) {
        if ((clients[num_clients++] = accept(fd, NULL, NULL)) == -1) {
            perror("accept error");
            continue;
        }
        printf("we got a connection!\n");
    }


    for (i = 0; i < num_clients; i++) {

        if (FD_ISSET(clients[i], &read_set)) {
            msg = read(clients[i], buf, sizeof(buf));
            if (msg > 0) {
                int savedclnt = clients[i];
                printf("client %d says: %s\n", i, buf);

                for (int p = 0; p<num_clients; p++)
                {
                    if (clients[p] != savedclnt) {
                        //write("from %d",clients[p]);
                        //char msg2 = strcat(clients[i],msg);
                        write(clients[p], buf, msg);
                    }

                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

对于你正在做的事情,你并不真正需要线程。根据个人经验,单线程服务器可以很好地完成工作。你应该使用accept()来查看哪些文件描述符有输入,而不是让主体环绕select()的调用,而不是...... {/ p>

fd_set readfds;
struct timeval timeout;
unsigned int num_clients;
unsigned int clients[100];
while(1)
  {
  FD_ZERO(&readfds);
  FD_SET(sock, &readfds);
  for(i=0; i<num_clients; i++)
    {
    FD_SET(clients[i],&readfds);
    }
  timeout.tv_sec=1;
  timeout.tv_usec=0;
  select(max_fds, &readfds, NULL, NULL, &timeout);
  if(FD_ISSET(sock,&readfds))
    {
    clients[num_clients++] = accept(sock,(struct sockaddr *)&server,&size);
    }
  for(i=0;i<num_clients;i++)
    {
    if(FD_ISSET(clients[i],&readfds))
      {
      int err=read(clients[i],buf,1000);
      if(err>0)
        {
        for(p=0;p<num_clients;p++)
          {
          write(clients[i],buf,err);
          }
        }
      }
    }
  }

该代码只是一个示例,需要进行错误检查以查看客户端是否已断开连接,这是一种更新客户端列表并查看客户端是否已准备好接收数据的方法。但希望它能为您提供去哪儿的基本想法?