c - 在c中使用socket选择阻塞

标签 c multithreading sockets select chat

下面的代码是一个聊天室。首先我运行服务器,然后运行客户端。客户端通过套接字到达服务器。然后服务器接受连接,客户端必须输入他的昵称。 我使用线程是因为这样,fgets 不会阻塞,并且即使客户端输入昵称的速度很慢,多个客户端也可以到达服务器。 到这里为止,没有任何问题,一切正常,甚至选择。

此后,客户端可以引入一条消息,该消息发送给所有客户端(这就是聊天的原理:P)。问题是,从这里开始,选择不会使用react并保持阻塞状态。也许是因为 FD_set 或线程,但实际上我不知道,这就是问题所在。

服务器.c:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <pthread.h>


#define MYPORT 5555
#define PSEUDO_MAX 30
#define MESSAGE_MAX 1000

#define BACKLOG 10



struct User {
  char pseudo[PSEUDO_MAX];
  int socket;
  struct User *next;
};

struct Thread {
  struct User* lst;
  fd_set* readfds;
  int* max;
  int socket;
  pthread_mutex_t* mutex;
};

void add(struct User** pp, const char *t, const int sock)
{
    struct User *p = malloc(sizeof(*p));
    strcpy(p->pseudo, t);
    p->socket = sock;
    p->next = NULL;

    while (*pp)
        pp = &(*pp)->next;
    *pp = p;
}

void print(const struct User* n) 
{
    for ( ; n; n = n->next ){
        printf("LISTE : %s\n", n->pseudo);
        printf("LISTE : %d\n", n->socket);
    }
    printf("\n");
}

void *thread_pseudo(void *arg)
{
  struct Thread* ps_thread = (struct Thread*)arg;
  int nsock = ps_thread->socket;
  struct User* lst = ps_thread->lst;
  int* max = ps_thread->max;
  pthread_mutex_t* mutex = ps_thread->mutex;
  pthread_mutex_lock(mutex);
  fd_set* readfds = ps_thread->readfds;
  pthread_mutex_unlock(mutex);

    char pseudo[PSEUDO_MAX];
    if (send(nsock, "Bienvenue sur le chat !\n",24,0)==-1){
      perror("Serveur: send");
    }

    if (recv(nsock, pseudo, PSEUDO_MAX, 0) == -1) {
      perror("Serveur: recv 2: ");
    }

    pthread_mutex_lock(mutex);

    FD_SET(nsock, readfds); // Ajout du nouveau socket au select
    *max = (nsock < *max ? *max : nsock);

    pthread_mutex_unlock(mutex);

    add(&lst, pseudo, nsock);
    print(lst);



    pthread_exit(NULL);
}

int findSender(fd_set* readfds, const struct User* n){
  int socket = 0;
  for ( ; n; n = n->next ){
    if(FD_ISSET(n->socket, readfds)){
      socket = n->socket;
    }
  }
  return socket;
}

int main()
{
  pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;


  int sockfd2, new_fd;  // listen on sock_fd, new connection on new_fd
  int max;
  struct sockaddr_in my_addr;  // my address information
  struct sockaddr_in their_addr; // connector's address information
  unsigned int sin_size;
  int yes=1;
  struct User *lst = NULL; // Initialisation de la liste des Users
  struct Thread *ps_thread = malloc(sizeof(*ps_thread)); // Initialisation du struct qui contient les paramètres pour le thread
  fd_set readfds;


  if ((sockfd2 = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
    perror("Serveur: socket 2");
    return EXIT_FAILURE;
  }

  if (setsockopt(sockfd2,SOL_SOCKET,SO_REUSEADDR, &yes,sizeof(int)) == -1) {
    perror("Serveur: setsockopt 2");
    return EXIT_FAILURE;
  }

  my_addr.sin_family = AF_INET;        
  my_addr.sin_port = htons(MYPORT);   
  my_addr.sin_addr.s_addr = INADDR_ANY;
  memset(&(my_addr.sin_zero), '\0', 8);

  if (bind(sockfd2, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
    perror("Serveur: bind 2");
    return EXIT_FAILURE;
  }

  if (listen(sockfd2, BACKLOG) == -1) {
    perror("Serveur: listen 2");
    return EXIT_FAILURE;
  }

  //Initialisation du fd_set et du max    
  FD_ZERO(&readfds);
  FD_SET(sockfd2, &readfds);
  max = sockfd2;



  while(1){
    if (select(max+1, &readfds, NULL, NULL, NULL) < 0){
      printf("error select\n");
    }

    int sock = findSender(&readfds, lst);

    if(FD_ISSET(sockfd2, &readfds)){
      new_fd = accept(sockfd2, (struct sockaddr *)&their_addr, &sin_size);

      if (new_fd == -1) { 
      perror("Serveur: accept");
      }

      pthread_t thread; 
      ps_thread->lst = lst;
      ps_thread->readfds = &readfds;
      ps_thread->max = &max;
      ps_thread->socket = new_fd;
      ps_thread->mutex = &mutex;

      if (pthread_create(&thread, NULL, thread_pseudo, ps_thread)) {
      perror("pthread_create");
      return EXIT_FAILURE;
      }
    }

    else if(FD_ISSET(sock, &readfds)) {
      char* message;
      int sock = findSender(&readfds, lst);
      if (recv(sock, message, MESSAGE_MAX, 0) == -1) {
        perror("Serveur: recv 2: ");
      }
    }

    else{
      printf("ERROR\n");
    }
  }

  return EXIT_SUCCESS;
}

客户端.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <pthread.h>

#define PORT 5555
#define PSEUDO_MAX 30
#define MESSAGE_MAX 1000


void getPseudo(char* pseudo) {
  size_t ln = -1;
  while (ln <= 0 || ln > PSEUDO_MAX-1) {
    printf("Entrez votre pseudo : ");
    fgets(pseudo, PSEUDO_MAX, stdin);
    ln = strlen(pseudo) - 1;
  }

  if (pseudo[ln] == '\n')
    pseudo[ln] = '\0';
}

void getMessage(char* message) {
  size_t ln = -1;
  while (ln <= 0 || ln > MESSAGE_MAX-1) {
    printf(">");
    fgets(message, MESSAGE_MAX, stdin);
    ln = strlen(message) - 1;
  }

  if (message[ln] == '\n')
    message[ln] = '\0';
}

void *thread_message(void *arg)
{
  printf("Bonjour\n");
  char* message;
  message = malloc (sizeof(char) * MESSAGE_MAX);
  int* sockfd = (int*)arg;
  printf("%d\n", *sockfd);

  while (1) {
    getMessage(message);
    if (send(*sockfd, message, strlen(message), 0) == -1){
      perror("Client: send message");
    }
  }
  pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
  int sockfd, numbytes;  
  struct sockaddr_in their_addr;
         // connector's address information 
  struct hostent *he;
  char buf[MESSAGE_MAX];
  long int term1, term2, res;
  int demande_pseudo = 0;
  char* pseudo;
  pseudo = malloc (sizeof(char) * PSEUDO_MAX);

  if (argc != 2) {
    fprintf(stderr, "Donner le nom du serveur.");
    return EXIT_FAILURE;
  }

  if ((he=gethostbyname(argv[1])) == NULL) {
    perror("Client: gethostbyname");
    return EXIT_FAILURE;
  }

  if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
    perror("Client: socket");
    return EXIT_FAILURE;
  }





  their_addr.sin_family = AF_INET;    
  their_addr.sin_port = htons(PORT);
  their_addr.sin_addr = *((struct in_addr*)he->h_addr);
  memset(&(their_addr.sin_zero), '\0', 8); 

  if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) {
    perror("Client: connect");
    return EXIT_FAILURE;
  }

  while (1) { 
    if ((numbytes=recv(sockfd, buf, MESSAGE_MAX-1, 0)) == -1) {
      perror("Client: recv");
      return EXIT_FAILURE;
    }

    if (demande_pseudo == 0) {
      buf[numbytes] = '\0';
      printf("%s",buf);
      getPseudo(pseudo);
      printf("Tu as choisi comme pseudo : %s\n", pseudo);
      demande_pseudo++;
      printf("%d\n", sockfd);
      if (send(sockfd, pseudo, strlen(pseudo), 0) == -1){
        perror("Client: send pseudo");
        return EXIT_FAILURE;
      }

      pthread_t thread; 

      if (pthread_create(&thread, NULL, thread_message, &sockfd)) {
        perror("pthread_create");
      return EXIT_FAILURE;
      }
    }

    else
    {

    }

  }

  close(sockfd);
  return EXIT_SUCCESS;
} 

非常感谢您的帮助

最佳答案

首先,你的问题很困惑,尝试更具体地举一些例子。 如果我理解您的问题,那么您的问题是您的 select 配置为在阻止模式下运行。 这是有关如何将套接字标志设置为非阻塞模式的示例。

flags = fcntl(sock, F_GETFL, 0);
if(flags < 0)
    err(1, "%s: fcntl", __FUNCTION__);

ret = fcntl(sock, F_SETFL, flags | O_NONBLOCK);
if(ret < 0)
    err(1, "%s: fcntl:", __FUNCTION__); 

答案更新

嗯,你的问题之一是你的 main 函数不会等待你的线程更新 readfds 和 max ,因此在 select 时被错误的值阻止变量。您可以通过在创建线程 OR 之后添加 pthread_join(thread, NULL); 来解决这个问题,正如我首先所说的,将您的选择设置为非阻塞模式。

  • 使用第二种方法(非阻塞模式)有时你会 select 没有任何内容需要处理,因此您需要处理这个问题而不是崩溃。 我会用它。
  • 使用第一种方法 (pthread_join),您将无法处理传入的消息 在等待线程完成时发出请求,从而使拥有线程的整个目的失效:可用于处理传入请求。

尝试发展这些想法,您将使代码发挥作用! (:

关于c - 在c中使用socket选择阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27489849/

相关文章:

c - 当测试值接近 _int32 最大值或负数时程序崩溃,但在 _int16 以上时运行良好...我做错了什么?

c - 使用 malloc 分配字符串

java - 线程崩溃后的状态是什么?

c++ - 用于 C++ 的套接字 API 或库?

使用日志函数(没有 math.h)和数组计算 C 中的字母表

c - 可以用变量体定义一个类似函数的宏吗?

ios - block 执行后变量返回 null

java - SyncAdapter 不考虑主线程设置的静态变量

php - 通过套接字发送数据

c++ - 编写基于控制台的 C++ IRC 客户端