Question: Modify the client.c and server.c in this way: After the client receives This server has been contacted 1 times, instead of exit, the client sends
Modify the client.c and server.c in this way:
After the client receives This server has been contacted 1 times, instead of exit, the client sends back This client has been contacted 1 times to the server. The server then sends back This server has been contacted 2 times, the client sends back This client has been contacted 2 times to the server, and so on. That is, both the client and the server do not exit. They alternatively send messages to each other.
/////////////////////////////////////////////////////////////////////////////
client:
/* Create a socket. */
sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto);
if (sd < 0) {
fprintf(stderr, "socket creation failed ");
exit(1);
}
/* Connect the socket to the specified server. */
if (connect(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
fprintf(stderr,"connect failed ");
exit(1);
}
/* Repeatedly read data from socket and write to user.s screen. */
n = recv(sd, buf, sizeof(buf), 0);
while (n > 0) {
write(1,buf,n);
printf("n: %d ", n);
n = recv(sd, buf, sizeof(buf), 0);
}
printf("n: %d ", n);
/* Close the socket. */
closesocket(sd);
/* Terminate the client program gracefully. */
exit(0);
}
////////////////////////////////////////////////////////////////////////////////////////
server:
/* Create a socket */
sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto);
if (sd < 0) {
fprintf(stderr, "socket creation failed ");
exit(1);
}
/* Bind a local address to the socket */
if (bind(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
fprintf(stderr,"bind failed ");
exit(1);
}
/* Specify size of request queue */
if (listen(sd, QLEN) < 0) {
fprintf(stderr,"listen failed ");
exit(1);
}
/* Main server loop - accept and handle requests */
while (1) {
alen = sizeof(cad);
if ( (sd2=accept(sd, (struct sockaddr *)&cad, &alen)) < 0) {
fprintf(stderr, "accept failed ");
exit(1);
}
visits++;
sprintf(buf,"This server has been contacted %d time%s ",
visits,visits==1?".":"s.");
send(sd2,buf,strlen(buf),0);
closesocket(sd2);
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
