多线程服务器在不等待客户端连接的情况下退出

Multithread server exits without waiting for the connect from client

本文关键字:连接 情况下 退出 客户端 等待 服务器 多线程      更新时间:2023-10-16

Linux套接字编程问题。

我正在开发一个多线程服务器,它可以接受来自多个客户端的连接。我的问题是,当我运行以下代码时,它会创建10个线程,然后在不等待客户端连接的情况下退出。有人能告诉我我的代码出了什么问题吗?非常感谢。

// include the library for socket programming
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
// include other useful library
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <string>
#include <pthread.h>
#include <fstream>
#include <time.h>

using namespace std;
static int ListenSoc;
#define LISTENPORT 6000
#define THREADNUM 10
void *AcceptAndService(void *){
   int ClientSoc;
   socklen_t CliLen;
   struct sockaddr_in CliAdd;
   CliLen=sizeof(CliAdd);
   memset((char *)&CliAdd,0,sizeof(CliAdd));
   //accept the connect from the client to do the login
   if(ClientSoc=accept(ListenSoc,(struct sockaddr*)&CliAdd,&CliLen)){
      cout<<"connection from "<<inet_ntoa(CliAdd.sin_addr)<<" has foundn";
   }
   pthread_exit(NULL);
}

int main(){
    //create the thread
    pthread_t thread[THREADNUM];
    //Doing the listen
    struct sockaddr_in SerAdd;
    ListenSoc=socket(AF_INET,SOCK_STREAM,0);
    // set the address
    memset((char *)&SerAdd,0,sizeof(SerAdd));
    SerAdd.sin_port=htons(LISTENPORT);
    SerAdd.sin_family=AF_INET;
    SerAdd.sin_addr.s_addr = INADDR_ANY;
    //bind
    if(bind(ListenSoc,(struct sockaddr*)&SerAdd,sizeof(SerAdd))==-1)
      cout<<"Error in bind";
    else
      cout<<"Bind success";
    //listen
    if(listen(ListenSoc,5)==-1)
       cout<<"Error in listen";
    else
    cout<<"nt the register server is waiting for the connection...n"<<endl;

    //Accept the connect from client
    int i;
    for(i=0;i<THREADNUM;i++){
      cout<<"Accept thread "<<i<<" is being created"<<endl;
      pthread_create(&thread[i], NULL, AcceptAndService, NULL); 
    }
    return 0;
}

您必须在for循环之后调用pthread_join,以等待线程结束:

int i;
for(i=0;i<THREADNUM;i++){
  cout<<"Accept thread "<<i<<" is being created"<<endl;
  pthread_create(&thread[i], NULL, AcceptAndService, NULL); 
}
for(i=0;i<THREADNUM;i++){
  pthread_join(thread[i], NULL);
}