tcp线程多并发
#include
#define SERPORT 8888
#define SERIP "192.168.0.118"
#define BACKLOG 20
typedef struct
{
int newfd;
struct sockaddr_in cin;
}BMH;
void *fun1(void *sss)
{
int newfd=accept((BMH *)sss)->newfd;
struct sockaddr_in cin=((HMY *)sss)->cin;
char buff[1000];
while(1)
{
bzero(buff,sizeof(buff));
int len=recv(newfd,buff,sizeof(buff),0);
printf("收到%s:%d的信息%s\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),buff);
if(len==0)
{
printf("客户端退出");
break;
}
strcat(buff,"xxx");
send(newfd,buff,sizeof(buff),0);
printf("发送成功\n");
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
int oldfd=socket(AF_INET,SOCK_STREAM,0);
if(oldfd==-1)
{
perror("oldfd");
return -1;
}
int bmz=8;
if(setsockopt(oldfd,SOL_SOCKET,SO_REUSEADDR,&bmz,sizeof(bmz))==-1)
{
perror("setsockopt");
return -1;
}
printf("端口快速复用应用成功\n");
struct sockaddr_in sin={
.sin_failmy=AF_INET,
.sin_port=htons(SERPORT),
.sin_addr.s_addr=inet_addr(SERIP)
};
if(bind(oldfd,(struct sockaddr *)&sin,sizeof(sin))==-1)
{
perror(bind);
return -1;
}
if(listen(oldfd,BACKLOG)==-1)
{
perror("listen");
return -1;
}
printf("监听成功\n");
struct sockaddr_in cin;
int cinlen=sizeof(cin);
BMH MSG;
while(1)
{
int newfd=accept(oldfd,(struct sockaddr *)&cin,&cinlen);
if(newfd==-1)
{
perror("accept");
return -1;
}
printf("%s:%d客户端连接\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port));
MSG.newfd=newfd;
MSG.cin=cin;
pthread_t tid;
if(pthread_create(&tid,NULL,fun1,MSG)!=0)
{
perror("pthread_create");
return -1;
}
pthread_detach(tid);
}
return 0;
}
tcp进程多并发
#include
#define SERPORT 9999
#define SERIP "192.168.0.130"
#define BACKLOG 10
void hande(int sss)
{
if(sss==SIGCHLD)
{
while(waitpid(-1,NULL,WNOHANG)!=-1);
}
}
int main(int argc, const char *argv[])
{
#if 1
if(signal(SIGCHLD,hande)==SIG_ERR)//捕获子进程退出的信号
{
perror("signal");
return -1;
}
#endif
int oldfd = socket(AF_INET,SOCK_STREAM,0);//1、创建原始套接字
if(oldfd ==-1)
{
perror("socket");
return -1;
}
int kkk=666;
if(setsockopt(oldfd,SOL_SOCKET,SO_REUSEADDR,&kkk,sizeof(kkk))==-1)//端口号快速复用
{
printf("setsockopt");
return -1;
}
printf("端口快速复用成功\n");
struct sockaddr_in sin = {
.sin_family = AF_INET,
.sin_port = htons(SERPORT),
.sin_addr.s_addr = inet_addr(SERIP)
};
if(bind(oldfd,(struct sockaddr *)&sin,sizeof(sin))==-1)//2、绑定
{
perror("bind");
return -1;
}
if(listen(oldfd,BACKLOG)==-1)
{
perror("listen");
return -1;
}
//接下来创建子进程,父进程负责接收客户端请求,子进程负责数据收发
struct sockaddr_in cin;
int cinlen = sizeof(cin);
while(1)
{
int newfd = accept(oldfd,(struct sockaddr *)&cin,&cinlen);
if(newfd==-1)
{
perror("accept");
return -1;
}
printf("newfd = %d\n",newfd);
printf("%s:%d连接成功\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port));
pid_t pid = fork();
if(pid>0)
{
close(newfd);
}
else if(pid==0)
{
close(oldfd);
char buff[1024];
while(1)
{
int len = recv(newfd,buff,sizeof(buff),0);
if(len==0)
{
printf("客户端退出\n");
break;
}
printf("服务器收到信息:%s\n",buff);
strcat(buff,"^_^");
send(newfd,buff,sizeof(buff),0);
printf("发送成功\n");
}
exit(0);
}
else{
perror("fork");
return -1;
}
}
close(oldfd);
return 0;
}