2023-5-21作业补
搭建TCP客户端
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
//端口号
#define PORT 6666
#define IP "192.168.8.254" //网络IP
#define ERR_MSG(msg) do{printf("line:%d\n",__LINE__);perror(msg);return -1;}while(0) //报错宏
int main(int argc, const char *argv[])
{
//创建套接字
int cfd=socket(AF_INET,SOCK_STREAM,0);
if(cfd<0){ERR_MSG("socket");}printf("Socket create success! cfd=%d __%d__\n",cfd,__LINE__);
int reuse=1;
if(setsockopt(cfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))<0)
{ERR_MSG("setsockopt");}
//服务器IP端口绑定
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(PORT);
sin.sin_addr.s_addr=inet_addr(IP);
//重用端口号
if(connect(cfd,(struct sockaddr*)&sin,sizeof(sin))<0)
{ERR_MSG("connect");}printf("Server link success! __%d__\n",__LINE__);
//创建文件描述符
fd_set readfds,tempfds;
FD_ZERO(&tempfds);FD_ZERO(&readfds);FD_SET(cfd,&readfds);FD_SET(0,&readfds);
int maxfd=cfd, s_res=0,newfd=-1;struct sockaddr_in cin;socklen_t len=sizeof(cin);
char buf[128]="";ssize_t res=0;
while(1)
{
//创建select监听文件描述符
tempfds=readfds;
s_res=select(maxfd+1,&tempfds,NULL,NULL,NULL);
//触发描述符后 响应事件
if(0>s_res){ERR_MSG("select");}
else if(0==s_res)
{printf("Overun!\n");break;}
for(int i=0;i<=maxfd;i++)
{
//触发键盘输入事件
if(!FD_ISSET(i,&tempfds))continue;
if(0==i)
{
printf("Trigger keboard input event!\n");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
printf("buf=%s\n",buf);
}
//触发连接事件
if(i==cfd)
{
printf("Trigger client link event!\n");
newfd=accept(cfd,(struct sockaddr*)&cin,&len);
if(newfd<0){ERR_MSG("accept");}
printf("[%s:%d] The client link is successful! newfd=%d __%d__ \n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,__LINE__);
FD_SET(newfd,&readfds);
maxfd=maxfd<newfd?newfd:maxfd;
}
//触发交互事件
else
{
printf("Trigger client intercaction events! __%d__\n",__LINE__);
bzero(buf,sizeof(buf));res=recv(i,buf,sizeof(buf),0);
if(res<0){ERR_MSG("recv");}
//触发下线事件
else if(0==res)
{
printf("[%s:%d] The client is offline! newfd=%d __%d__\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),i,__LINE__);
close(i);FD_CLR(i,&readfds);
while(!FD_ISSET(maxfd,&readfds)&&maxfd-->=0);continue;
}
printf("[%s:%d] newfd=%d:%s,__%d__\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),i,buf,__LINE__);
strcat(buf,"*_*");
if(send(i,buf,sizeof(buf),0)<0){ERR_MSG("send");}
printf("Transmit success!\n");
}
}
}
//关闭套接字
close(cfd);
return 0;
}