IO同時マルチプロセスおよびマルチスレッド実装
1837 ワード
サーバdemo:
#include "lib.h" //
#define SERVER_PORT 6666
//
void * pthread_fun(void *arg)
{
char buf[1024]={0};
int confd=*(int *)arg;
while(1)
{
memset(buf,0,sizeof(buf));
if(recv(confd,buf,sizeof(buf),0)==0)
{
return NULL;
}
printf("buf=%s
",buf);
}
}
int main()
{
int i=0;
pthread_t tid[1024]={0};
int serverSocket;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
int addr_len=sizeof(client_addr);
int client;
int iDataNum;
char buf[1024];
if((serverSocket=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("Socket");
exit(1);
}
bzero(&server_addr,sizeof(server_addr));
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(SERVER_PORT);
server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
//
int on;
if(setsockopt(serverSocket,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(int))<<0)
{
perror("setsockopt error
");
return 0;
}
if(bind(serverSocket,(struct sockaddr *)&server_addr,\
sizeof(server_addr))<0)
{
perror("bind");
exit(1);
}
listen(serverSocket,5);
while(1)
{
client=accept(serverSocket,(struct sockaddr *)&client_addr,\
&addr_len);
if(client==-1)
{
perror("accept");
return -1;
}
pthread_create(&tid[i++],NULL,pthread_fun,&client);
/*
if(fork()==0)
{
while(1)
{
memset(buf,0,sizeof(buf));
iDataNum=recv(client,buf,1024,0);
if(iDataNum<=0)
{
perror("Recv");
return -1;
}
printf("
Recv client data.....
");
printf("recv data is %s
",buf);
send(client,buf,sizeof(buf),0);
}
}
*/
}
close(client);
close(serverSocket);
return 0;
}