client端
1.创建套接字并且建立连接请求
int sockfd = 0;
int ret = 0;
struct sockaddr_in seraddr;
seraddr.sin_family = AF_INET;
seraddr.sin_port = htons(port);
seraddr.sin_addr.s_addr = inet_addr(SER_IP);
sockfd = socket(AF_INET,SOCK_STREAM,0);
if(-1 == sockfd)
{
return -1;
}
ret = connect(sockfd,(struct sockaddr *)&seraddr,sizeof(seraddr));
if(-1 == ret)
{
return -1;
}
return sockfd;
2.向对方发送 接收
char tmpbuff[4096] = {0};
static int cnt = 0;
ssize_t nsize = 0;
sprintf(tmpbuff,"hello world---%d",cnt);
nsize = send(sockfd,tmpbuff,strlen(tmpbuff),0);
if(-1==nsize)
{
return -1;
}
cnt++;
memset(tmpbuff,0,sizeof(tmpbuff));
nsize = recv(sockfd,tmpbuff,sizeof(tmpbuff),0);
if(-1 == nsize)
{
return -1;
}
else if(0==nsize)
{
return 0;
}
printf("RECV:%s\n",tmpbuff);
return nsize;
server端
1.创建套接字并监听
socket(AF_INET,SOCK_STREAM,0);
bind(sockfd,(struct sockaddr *)&seraddr,sizeof(seraddr));
listen(sockfd,10);
2.将sockfd加入监听集合中
FD_ZERO(&rdfds);
FD_SET(sockfd,&rdfds);
maxfd = sockfd;
3.开始监听
tmpfds = rdfds;
select(maxfd+1,&tmpfds,NULL,NULL,NULL);
4.如果sockfd产生事件,处理新的连接请求,并将新的文件描述符加入集合,下次一起监听
if(FD_ISSET(sockfd,&tmpfds));
confd = accept(sockfd,NULL,NULL);
maxfd = maxfd>confd?maxfd:confd;
FD_SET(confd,&rdfds);
5.遍历所有已经连接的客户端中是否有事件发生
if(FD_ISSET(i,&tmpfds);