客户端代码,和一般的客户端不一样
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXDATASIZE 100
int main()
{
int sockfd,nbytes,serv_port;
char buf_serv_ip[16],buf[260];
struct sockaddr_in serv_addr;
if((sockfd=socket(/*AF_INET,SOCK_STREAM,0*/PF_INET, SOCK_STREAM, IPPROTO_TCP))==-1){
perror("创建套接字失败!\n");
exit(1);
}
//创建套接字成功后设置其可重用的属性
int KeepAlive=1;
socklen_t KPlen=sizeof(int);
if(setsockopt(sockfd,SOL_SOCKET,SO_KEEPALIVE,(char *)&KeepAlive,KPlen)!=0){
perror("设置周期测试连接是否仍存活失败!\n");
exit(1);
}
int keepIdle = 10;//每次检测的相隔时间
int keepInterval = 1;//检测前的空间时间
int keepCount = 3;//最大检测次数
setsockopt(sockfd,SOL_TCP,TCP_KEEPINTVL,(void *)&keepIdle,sizeof(keepIdle));
setsockopt(sockfd,SOL_TCP,TCP_KEEPIDLE,(void *)&keepInterval,sizeof(keepInterval));
setsockopt(sockfd,SOL_TCP,TCP_KEEPCNT,(void *)&keepCount,sizeof(keepCount));
printf("请输入要连接主机的IP地址:\n");
scanf("%s",buf_serv_ip);
printf("请输入要连接主机的端口号:\n");
scanf("%d",&serv_port);
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr(buf_serv_ip);
serv_addr.sin_port=htons(serv_port);
bzero(&(serv_addr.sin_zero),8);
if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(struct sockaddr))==-1){
perror("连接服务器失败!\n");
exit(1);
}
if((getsockopt(sockfd,SOL_SOCKET,SO_KEEPALIVE,(char*)&KeepAlive,&KPlen))==0){
printf("SO_KEEPALIVE Value: %d\n", KeepAlive);
}
printf("连接服务器成功!\n");
//在此处可以先接受判断将要接受数据的长度再创建数组
int i =0;
int res = 0;
int errcode;
fd_set readmask;
struct timeval timeout;
while(1){
FD_ZERO(&readmask);
FD_SET(sockfd, &readmask);
timeout.tv_sec = 1;
timeout.tv_usec = 0;
if ((res = select(sockfd + 1, &readmask, NULL, NULL, &timeout)) < 0)
{
printf("the socket is error\n");
exit(1);
}
printf("select return %d\n", res);
if(res == 0)
{//检测连接是否超时,可能服务器长时间没发数据
int sockfdtemp;
errno = 0;
printf("连接超时\n");
/*
if((sockfdtemp=socket(AF_INET,SOCK_STREAM,0))==-1){
perror("超时接字失败!\n");
exit(1);
}
if(connect(sockfdtemp,(struct sockaddr *)&serv_addr,sizeof(struct sockaddr))==-1){
printf("超时连接服务器失败!\n");
errcode = errno;u
//close(sockfdtemp);
if (errcode != ENOENT && errcode != ECONNREFUSED) {
printf("Failed to establish connection: %d\n", errcode);
}
//continue;
//exit(1);
}else
{
printf("服务器没挂!\n");
//close(sockfdtemp);
}
close(sockfdtemp);
*/
continue;
}
/* 处理Slave端连接请求 */
if( (sockfd != -1 ) && FD_ISSET(sockfd, &readmask) )
{
printf("the socket is ok\n");
memset(buf, 0, 260);
errno = 0;
if((nbytes=recv(sockfd,buf,260,0))==-1){
printf("接受数据失败!\n");
errcode = errno;
if(errcode == ETIMEDOUT)
{//服务器真正的挂掉
printf("******服务器挂掉 %d : %d \n", errno, ETIMEDOUT);
exit(1);
}
}
if (nbytes == 0)
{
printf("数据为空: %d\n", i);
}
else
{
buf[nbytes]='\0';
printf("接受的数据为:%d\n", i);
}
}else
{
printf("the socket is not OK\n");
exit(1);
}
i++;
}
close(sockfd);
return 0;
}