多线程服务器不等待客户端连接就退出
Posted
技术标签:
【中文标题】多线程服务器不等待客户端连接就退出【英文标题】:Multithread server exits without waiting for the connect from client 【发布时间】:2014-11-11 20:37:37 【问题描述】: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】:你必须在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);
【讨论】:
非常感谢,它有效。一开始我以为accept在某个客户端尝试连接到服务器之前不会执行,所以每个线程都会在accept语句处停止,如果连接没有建立,pthread_exit(NULL)也不会执行。以上是关于多线程服务器不等待客户端连接就退出的主要内容,如果未能解决你的问题,请参考以下文章