2023-5-18作业
编写多线程服务器
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>
#include <pthread.h>
#define ERR_MSG(msg) do{printf("line:%d\n",__LINE__);perror(msg);}while(0)
#define PORT 6666 //端口
#define IP "192.168.8.62" //机器IP
//线程体
struct climsg
{
int newfd;
struct sockaddr_in cin;
};
void*deal_cli_msg(void*arg);
int main(int argc,const char*argv[])
{
//套接字
int sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd<0)
{
ERR_MSG("socket");;
return -1;
}
printf("socket create success sfd=%d __%d__\n",sfd,__LINE__);
//端口重用
int reuse=1;
if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))<0)
{
ERR_MSG("setsockopt");
return -1;
}
//服务器地址
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(PORT);
sin.sin_addr.s_addr=inet_addr(IP);
//描述符
if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))<0)
{
ERR_MSG("bind");
return -1;
}
printf("bind success __%d__\n",__LINE__);
//监听
if(listen(sfd,128)<0)
{
ERR_MSG("listen");
return -1;
}
printf("listen success __%d__\n",__LINE__);
//存储客户信息
struct sockaddr_in cin;
socklen_t len=sizeof(cin);
int newfd=-1;
pthread_t tid;
struct climsg info;
while(1)
{
//链接客户端
newfd=accept(sfd,(struct sockaddr*)&cin,&len);
if(newfd<0)
{
perror("accept");
return -1;
}
printf("[%s:%d] Client link success! newfd%d __%d__\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,__LINE__);
info.newfd=newfd;
info.cin=cin;
//分支交互
if(pthread_create(&tid,NULL,deal_cli_msg,&info)!=0)
{
fprintf(stderr,"pthread_create faile __%d__\n",__LINE__);
return -1;
}
pthread_detach(tid); //回收资源
}
if(close(sfd)<0)
{
ERR_MSG("close");
return -1;
}
return 0;
}
//与客户端交互
void*deal_cli_msg(void*arg)
{
int newfd=((struct climsg*)arg)->newfd;
struct sockaddr_in cin=((struct climsg*)arg)->cin;
char buf[128]="";
ssize_t res=0;
while(1)
{
bzero(buf,sizeof(buf));
//接收数据
res=recv(newfd,buf,sizeof(buf),0);
if(res<0)
{
ERR_MSG("recv");
break;
}
else if(0==res)
{
printf("[%s:%d] Client quit newfd=%d __%d__\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,__LINE__);
break;
}
printf("[%s:%d] newfd=%d:%s,__%d__\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,buf,__LINE__);
//回发
strcat(buf,"*_*");
if(send(newfd,buf,sizeof(buf),0)<0)
{
ERR_MSG("send");
break;
}
printf("Transmit success!\n");
}
if(close(newfd)<0)
{
ERR_MSG("close");
}
pthread_exit(NULL);
}