#include<myhead.h>
#define SERIP "192.168.0.161"
#define SERPORT 9999
#define listensize 10
typedef struct
{
int newsocket;
struct sockaddr_in cln;
}Ccln;
void *trans(void*arg)
{
Ccln *cln = (Ccln*)arg;
char buff[1024];
while(1)
{
memset(buff,0,sizeof(buff));
//6.1 recv send
int len =recv(cln->newsocket,buff,sizeof(buff),0);
if(len == 0)
{
printf("客户端退出\n");
break;
}
printf("收到来自%s:%d客户端的信息:%s\n",inet_ntoa(cln->cln.sin_addr),ntohs(cln->cln.sin_port),buff);
strcat(buff,"1");
send(cln->newsocket,buff,sizeof(buff),0);
//6.2 p_exit
pthread_exit(NULL);
}
}
int main(int argc, const char *argv[])
{
//1,socket
int oldsocket = socket(AF_INET,SOCK_STREAM,0);
if(oldsocket==-1)
{
perror("socket");
return -1;
}
//2.setsockopt
int k=1;
if(setsockopt(oldsocket,SOL_SOCKET,SO_REUSEADDR,&k,sizeof(k))==-1)
{
perror("setsockopt");
return -1;
}
printf("设置复用端口成功\n");
//3.bind
struct sockaddr_in sln={
.sin_family=AF_INET,
.sin_addr = inet_addr(SERIP),
.sin_port = htons(SERPORT)
};
if(bind(oldsocket,(struct sockaddr*)&sln,sizeof(sln))==-1)
{
perror("bind");
return -1;
}
//4.listen
if(listen(oldsocket,listensize)==-1)
{
perror("listen");
return -1;
}
//5.accept in circle
struct sockaddr_in cln;
int clnlen =sizeof(cln);
while(1)
{
int newsocket = accept(oldsocket,(struct sockaddr*)&cln,&clnlen);
if(newsocket==-1)
{
perror("accept");
return -1;
}
printf("%s:%d发出请求连接\n",inet_ntoa(cln.sin_addr),ntohs(cln.sin_port));
//6.p_create
Ccln clninfo;
clninfo.newsocket = newsocket;
clninfo.cln = cln;
pthread_t tid;
if(pthread_create(&tid,NULL,trans,&clninfo)!=0)
{
perror("pthread_create");
return -1;
}
printf("发送成功\n");
//7.p_detach
pthread_detach(tid);
}
//8.close
close(oldsocket);
return 0;
}