1、TCP并发客户端,用select 实现
#include<myhd.h>
#define CLIPORT 8888
#define CLIIP "192.168.115.141"
int main(int argc, const char *argv[])
{
//创建客户端套接字
int cfd=socket(AF_INET,SOCK_STREAM,0);
if(cfd==-1)
{
perror("socket perror");
return -1;
}
printf("socket success\n");
//绑定服务器(可选)
//进行连接服务器
//1、填充地址信息结构
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(CLIPORT);
sin.sin_addr.s_addr=inet_addr(CLIIP);
if(connect(cfd,(struct sockaddr*)&sin,sizeof(sin))==-1)
{
perror("connect error");
return -1;
}
printf("connect success\n");
//创建检测文件描述符的集合
fd_set readfds,tempfds;
FD_ZERO(&readfds);
FD_ZERO(&tempfds);
FD_SET(0,&readfds);
FD_SET(cfd,&readfds);
//进行通信
char buf[128]="";
char rbuf[128]="";
int res=0;
while(1)
{
tempfds=readfds;
res=select(cfd+1,&tempfds,NULL,NULL,NULL);
if(res==-1)
{
perror("select error");
return -1;
}
else if(res==0)
{
printf("time out\n");
return -1;
}
if(FD_ISSET(0,&tempfds))
{
bzero(buf,sizeof(buf));
bzero(rbuf,sizeof(rbuf));
fgets(buf,sizeof(buf),stdin);
send(cfd,buf,sizeof(buf),0);
}
if(FD_ISSET(cfd,&tempfds))
{
if(strcmp(buf,"quit")==0)
{
break;
}
int res=recv(cfd,rbuf,sizeof(rbuf),0);
printf("%s",rbuf);
if(res==0)
{
printf("服务器已经关闭\n");
break;
}
}
}
//关闭客户端套接字
close(cfd);
return 0;
}
2、用Poll实现UDP并发客户端