#include #define SERVER_PORT 6666
#define BUFES 20
int main(void)
{
int fd_clint;
int n;
struct sockaddr_in clint_addr;
bzero(&clint_addr, sizeof(clint_addr));
clint_addr.sin_family = AF_INET;
clint_addr.sin_port = htons(SERVER_PORT);
clint_addr.sin_addr.s_addr = INADDR_ANY;
fd_clint = socket(AF_INET, SOCK_STREAM, 0);
if(fd_clint < 0)
{
perror("fail to socket\n");
exit(1);
}
if(connect(fd_clint, (struct sockaddr*)&clint_addr, sizeof(clint_addr)) < 0)
{
perror("fail to connect\n");
exit(1);
}
fd_set readfds;
int max_fd = fd_clint + 1;
while(1)
{
FD_ZERO(&readfds);
FD_SET(0, &readfds);
FD_SET(fd_clint, &readfds);
char buf[BUFES];
printf("Please enter command!\n");
if(select(max_fd, &readfds, NULL, NULL, NULL) > 0)
{
if(FD_ISSET(0, &readfds))
{
scanf("%s", buf);
n = send(fd_clint, buf, BUFES, 0);
if(n < 0)
{
perror("send falied\n");
exit(1);
}
}
if(FD_ISSET(fd_clint, &readfds))
{
n = read(fd_clint, buf, BUFES);
if(n == 0)
{
perror("server has closed \n");
exit(1);
}
else if(n < 0)
{
perror("socket failed\n");
exit(1);
}
}
}
}
if(close(fd_clint) < 0)
{
perror("fail to close fd_clint\n");
exit(1);
}
return 0;
}