/* 修改 ex4 部分用藍色表示 */
//-------------------------------------------------------------------------------------------
//tcpcli01.c
#include "unp.h"
struct ans
{
int answer;
};
void guess(FILE *fp, int sockfd)
{
char sendline[MAXLINE], recvline[MAXLINE];
struct ans ans;
printf("Please guess a number between 1 and 100:\n");
do {
if (Fgets(sendline, MAXLINE, fp) != NULL) {
if (sscanf(sendline, "%d", &ans.answer)!=1)
printf("Invalid input: %s", sendline);
else if (ans.answer>100 || ans.answer<1)>");
sockfd = Socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
Connect(sockfd, (SA *) &servaddr, sizeof(servaddr));
guess(stdin, sockfd); /* do it all */
exit(0);
}
//-------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------
//tcpserv01.c
#include "unp.h"
struct ans
{
int answer;
};
void retrt(int sockfd)
{
char buf[MAXLINE];
ssize_t n;
struct ans ans;
int result;
srand(time(NULL));
result=rand()%100+1;
printf("The answer is %d\n",result);
do {
if ( (n = Readn(sockfd, &ans, sizeof(ans))) == 0)
return; /* connection closed by other end */
if (ans.answer>result) strcpy(buf,"Guess a smaller number!\n");
else if (ans.answer
else strcpy(buf,"You got the answer!\n");
Writen(sockfd, buf, strlen(buf));
} while (strcmp(buf,"You got the answer!\n")!=0);
}
int main(int argc, char **argv)
{
int listenfd, connfd;
pid_t childpid;
socklen_t clilen;
struct sockaddr_in cliaddr, servaddr;
listenfd = Socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));
Listen(listenfd, LISTENQ);
for ( ; ; ) {
clilen = sizeof(cliaddr);
connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);
if ( (childpid = Fork()) == 0) { /* child process */
Close(listenfd); /* close listening socket */
retrt(connfd); /* process the request */
exit(0);
}
Close(connfd); /* parent closes connected socket */
}
}
//-------------------------------------------------------------------------------------------
沒有留言:
張貼留言