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;
}
스레드가 끝날 때까지 기다리려면 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);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다