Several clients send strings to the server. The server compares them and sends information to clients. TCP communication protocol

Actually now the client sends the line, the server receives it and sends it back. And you need to make sure that 1 client sends a string - in response, nothing, 2 client sends - in response to both the result of calculations, then 3 sends - in response, a different result to all 3 clients. C / C ++ language

Server

#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> int main() { int sock, listener; struct sockaddr_in addr; char buf[1024]; int bytes_read; listener = socket(AF_INET, SOCK_STREAM, 0); if(listener < 0){ perror("socket"); exit(1); } addr.sin_family = AF_INET; addr.sin_port = htons(3425); addr.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(listener, (struct sockaddr *)&addr, sizeof(addr)) < 0){ perror("bind"); exit(2); } listen(listener, 1); while(1){ sock = accept(listener, NULL, NULL); if(sock < 0){ perror("accept"); exit(3); } while(1){ bytes_read = recv(sock, buf, 1024, 0); if(bytes_read <= 0) break; send(sock, buf, bytes_read, 0); } close(sock); } return 0; } 

Customer

 #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> char message[] = "Hello there!\n"; char buf[sizeof(message)]; int main() { int sock; struct sockaddr_in addr; sock = socket(AF_INET, SOCK_STREAM, 0); if(sock < 0){ perror("socket"); exit(1); } addr.sin_family = AF_INET; addr.sin_port = htons(3425); // или любой другой порт... addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0){ perror("connect"); exit(2); } send(sock, message, sizeof(message), 0); recv(sock, buf, sizeof(message), 0); printf(buf); printf("sock = %d", sock); close(sock); return 0; } 
  • one
    If there is not a lot of customers, look at the select() function man7.org/linux/man-pages/man2/select.2.html . If a lot - look in the direction of epoll() . This is so that waiting for data from one client does not stop the server and you could independently expect data from several clients. And it's not difficult to send, you will surely have some sort of an array of client connections, bypass it and make a send for everyone - Mike
  • Explain the problem more precisely. - Cerbo

1 answer 1

The easiest way to use the library is libevent , here is an example of the implementation of the server using this library. Libevent library for asynchronous non-blocking i / o, Part 4. Network applications

I can also recommend a classic solution using the fork function