I writing server and client on sockets in c . I have a server running for one client. Tell me how to use fork
to write a multiuser server.
server:
int main() {
int server_socket = Socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in adr = {0};
adr.sin_family = AF_INET;
adr.sin_port = htons(1110);
Bind(server_socket, (struct sockaddr* )&adr, sizeof(adr));
Listen(server_socket, SOMAXCONN);
socklen_t adr_len = sizeof(adr);
int res_accept = Accept(server_socket, (struct sockaddr* ) &adr, &adr_len);
while(true) {
char buffer[1024];
ssize_t count_read = Recv(res_accept, buffer, 1024, 0);
printf("%s\n", buffer);
fflush(stdin);
char res[10];
int result = words_counter(buffer);
sprintf(res, "%d\n", result);
ssize_t count_send = Send(res_accept, res, 10, 0);
}
close(res_accept);
close(server_socket);
return 0;
}
client:
int main(int argc, char const *argv[]) {
int client_socket = Socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in adr = {0};
adr.sin_family = AF_INET;
adr.sin_port = htons(1110);
Inet_pton(AF_INET, "127.0.0.1", &adr.sin_addr);
int res_connect = Connect(client_socket, (struct sockaddr* ) &adr, sizeof(adr));
while (true) {
char message[1024];
printf("input message\n");
fgets(message, 1024, stdin);
if (strncmp(message, "quit!", 5) == 0) break;
ssize_t count_send = Send(client_socket, message, 1024, 0);
char buffer[10];
ssize_t count_read = Recv(client_socket, buffer, 10, 0);
printf("SERVER: The number of words in the transmitted message: %s", buffer);
}
close(client_socket);
return 0;
}
I use self-written wrapper functions (for convenient error handling) functions such as bind
, listen
, etc. Therefore, the function names are written with a capital letter.
Thank you for help
CodePudding user response:
Tell me how to use
fork
to write a multiuser server.
I take you to be asking how to adapt your existing server to serve multiple clients, by use of fork
. The simplest way to do this would be for
Put a loop around everything from the
Accept()
call toclose(res_accept)
. This provides for accepting multiple connections. If you wanted only to handle multiple clients sequentially then this would do it without any forking. But to be able to handle multiple clients concurrently,fork()
after accepting each connection. Have (only) the child execute thewhile
loop and then_exit()
. The parent will instead skip over thewhile
loop to theclose(res_accept)
. This frees the parent to accept more connections, while the child handles interaction with the newly-accepted client.