多线程服务器退出而不等待来自客户端的连接

时间:2014-11-11 20:37:38

标签: c++ multithreading sockets tcp

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 found\n";
   }
   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<<"\n\t 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;
}

1 个答案:

答案 0 :(得分: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);
}