1.socket客户端
#include <myhead.h>
#define SERIP "192.168.115.132"
#define SERPORT 8888
#define CLIIP "192.168.115.132"
#define CLIPORT 6666
int main(int argc, const char *argv[])
{
//创建套接字
int cfd=socket(AF_INET,SOCK_STREAM,0);
if(cfd==-1)
{
perror("socket error");
return -1;
}
//连接服务器
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(SERPORT);
sin.sin_addr.s_addr=inet_addr(SERIP);
if(connect(cfd,(struct sockaddr*)&sin,sizeof(sin))==-1)
{
perror("connect error");
return -1;
}
//收发数据
char buf[128]="";
char rbuf[128]="";
fd_set readfds,tempfds;
FD_ZERO(&readfds);
FD_SET(0,&readfds);
FD_SET(cfd,&readfds);
int res=0;
int maxfd=cfd;
while(1)
{
tempfds=readfds;
bzero(buf,sizeof(buf));
bzero(rbuf,sizeof(rbuf));
res=select(maxfd+1,&tempfds,NULL,NULL,NULL);
if(res==-1)
{
perror("select error");
return -1;
}else if(res==0)
{
printf("time out\n");
return -1;
}
for(int i=0;i<=maxfd;i++)
{
if(!FD_ISSET(i,&tempfds))
{
continue;
}
if(i==0)
{
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]='\0';
send(cfd,buf,sizeof(buf),0);
}
else if(i==cfd)
{
int res=recv(cfd,rbuf,sizeof(rbuf),0);
if(res==0)
{
printf("服务器关闭\n");
break;
}
printf("rbuf=%s\n",rbuf);
}
}
}
close(cfd);
return 0;
}
2.poll服务器端
#include <myhead.h>
#define PORT 8888
#define IP "192.168.1.7"
int main(int argc, const char *argv[])
{
//创建套接字
int sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd==-1)
{
perror("socket error");
return -1;
}
//快速重用
int reuse=1;
if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))==-1)
{
perror("setsockopt error");
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))==-1)
{
perror("bind error");
return -1;
}
//被动监听
if(listen(sfd,128)==-1)
{
perror("listen error");
return -1;
}
//定义客户端地址信息结构体
struct sockaddr_in cin;
cin.sin_family=AF_INET;
socklen_t socklen=sizeof(cin);
struct pollfd fds[1024];
fds[0].fd=0;
fds[0].events=POLLIN;
char buf[128]="";
int newfd=-1;
int maxfd=0;
int res=-1;
for(int i=0;i<=1024;i++)
{
fds[i].fd=-1;
}
struct sockaddr_in saveCin[1024];
while(1)
{
res=poll(fds,maxfd+1,-1);
if(res==-1)
{
perror("poll error");
return -1;
}else if(res==0)
{
continue;
}else if(res>0)
{
if(fds[0].revents==POLLIN)
{
newfd=accept(sfd,(struct sockaddr*)&cin,&socklen);
if(newfd==-1)
{
perror("accept error");
return -1;
}
for(int i=1;i<1024;i++)
{
if(fds[i].fd==-1)
{
fds[i].fd=newfd;
fds[i].events=POLLIN;
break;
}
}
if(newfd>maxfd)
{
maxfd=newfd;
}
}
for(int i=1;i<maxfd;i++)
{
if(fds[i].revents==POLLIN)
{
int ret=read(fds[i].fd,buf,sizeof(buf));
if(ret==-1)
{
perror("read error");
return -1;
}else if(ret==0)
{
printf("close\n");
close(fds[i].fd);
fds[i].fd=-1;
}else if(ret>0)
{
printf("buf=%s\n",buf);
write(fds[i].fd,buf,strlen(buf)+1);
}
}
}
}
}
close(sfd);
return 0;
}
3.思维导图