#include<my_head.h>
#define SERPORT 9999
#define SERIP "192.168.125.4"
#define CLIPORT 8888
#define CLIIP "192.168.125.4"
int main(int argc, const char *argv[])
{
//创建文件描述符
int cfd = -1;
if((cfd = socket(AF_INET,SOCK_STREAM,0)) == -1)
{
perror("");
return -1;
}
int reuse = 1;
if(setsockopt(cfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))==-1)
{
perror("");
return -1;
}
struct sockaddr_in cin;
cin.sin_family = AF_INET;
cin.sin_port = htons(CLIPORT);
cin.sin_addr.s_addr = inet_addr(CLIIP);
if(bind(cfd,(struct sockaddr*)&cin,sizeof(cin)) == -1)
{
perror("");
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("");
return -1;
}
printf("connect success\n");
fd_set readfds,tempfds;
FD_ZERO(&readfds);
FD_SET(cfd,&readfds);
FD_SET(0,&readfds);
int res = 0;
char rbuf[128]="";
char wbuf[128]="";
while(1)
{
tempfds = readfds;
res = select(cfd+1,&tempfds,NULL,NULL,NULL);
if(res == -1)
{
perror("");
return -1;
}
else if(res == 0)
{
printf("timeout\n");
return -1;
}
if(FD_ISSET(0,&tempfds))
{
bzero(wbuf,sizeof(wbuf));
printf("please input:");
fgets(wbuf,sizeof(wbuf),stdin);
wbuf[strlen(wbuf)-1] == 0;
send(cfd,wbuf,sizeof(wbuf),0);
if(strcmp(wbuf,"quit") == 0)
{
break;
}
}
if(FD_ISSET(cfd,&tempfds))
{
bzero(rbuf,sizeof(rbuf));
int n = recv(cfd,rbuf,sizeof(rbuf),0);
if(n == 0)
{
printf("服务端下线\n");
break;
}
printf("sever:%s\n",rbuf);
}
}
close(cfd);
return 0;
}