Question: // Function designed for chat between client and server. void func(int sockfd) { char buff[MAX]; int n; // infinite loop for chat for (;;) {
// Function designed for chat between client and server. void func(int sockfd) { char buff[MAX]; int n; // infinite loop for chat for (;;) { bzero(buff, MAX);
// copy server message in the buffer while ((buff[n++] = getchar()) != ' ')
Sol18:
This code defines a function named func() that takes a socket file descriptor as a parameter and implements the communication between the client and server using a loop.
Inside the function, a buffer named buff of size MAX is declared and initialized to all zeros using the bzero() function. An integer variable n is also declared and initialized to zero.
The code then enters an infinite loop using the for (;;) statement. Inside the loop, the buffer is cleared using bzero() and the server message is read from the standard input using getchar() function until a newline character is encountered. The message is then copied to the buffer using the buff[n++] = getchar() statement.
After the message has been copied to the buffer, the write() function is used to send the message to the server using the socket file descriptor. The number of bytes sent is returned by the write() function and stored in the variable n. If n is less than zero, an error message is printed and the program terminates.
Next, the bzero() function is used to clear the buffer again, and the read() function is used to receive the server's response from the socket. The received data is stored in the buffer, and the number of bytes read is returned by the read() function and stored in n. If n is less than zero, an error message is printed and the program terminates.
Finally, the received message is printed to the standard output using printf() function, and the loop continues to receive and send messages between the client and server.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
