From fe43eafb5cd475bb33ff39788dadf2590d8bc0e4 Mon Sep 17 00:00:00 2001 From: Daniel Meiburg Date: Fri, 17 May 2024 12:48:00 +0200 Subject: [PATCH] 04_intro_to_sockets: split communicate in tcp_write and tcp_read --- 04_intro_to_sockets/lib/sockets.c | 7 ++++--- 04_intro_to_sockets/lib/sockets.h | 5 +++-- 04_intro_to_sockets/src/daytimeTCPCli.c | 3 ++- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/04_intro_to_sockets/lib/sockets.c b/04_intro_to_sockets/lib/sockets.c index a7123fb..f426f2d 100644 --- a/04_intro_to_sockets/lib/sockets.c +++ b/04_intro_to_sockets/lib/sockets.c @@ -13,7 +13,6 @@ static void error_handling(char *message, int sock) { perror(message); if (sock != -1) close(sock); - close(sock); } int tcp_create_socket() { @@ -39,12 +38,14 @@ void connect_to_server(int sock, char *ip, int port) { error_handling("connect() error", sock); } -char* communicate(int sock, char *message) { +int tcp_write(int sock, char* message) { // Sending the ASCII string if (write(sock, message, strlen(message)) == -1) error_handling("write() error", sock); + return 0; +} - // Receiving response +char *tcp_read(int sock) { char* response = malloc(BUFFER_SIZE); if (!response) error_handling("Failed to allocate memory for response", sock); diff --git a/04_intro_to_sockets/lib/sockets.h b/04_intro_to_sockets/lib/sockets.h index 467f9c9..f30f722 100644 --- a/04_intro_to_sockets/lib/sockets.h +++ b/04_intro_to_sockets/lib/sockets.h @@ -7,8 +7,9 @@ int tcp_create_socket(); // Function to connect to a server void connect_to_server(int sock, char *ip, int port); -// Function to communicate with the server -char* communicate(int sock, char *message); +int tcp_write(int sock, char* message); + +char *tcp_read(int sock); // Function to create a TCP server socket int tcp_listen(int port); diff --git a/04_intro_to_sockets/src/daytimeTCPCli.c b/04_intro_to_sockets/src/daytimeTCPCli.c index 93badde..770d45d 100644 --- a/04_intro_to_sockets/src/daytimeTCPCli.c +++ b/04_intro_to_sockets/src/daytimeTCPCli.c @@ -11,7 +11,8 @@ int main(int argc, char *argv[]) { int sock = tcp_create_socket(); connect_to_server(sock, argv[1], atoi(argv[2])); - char* received_data = communicate(sock, argv[3]); + tcp_write(sock, argv[3]); + char* received_data = tcp_read(sock); if (received_data) { printf("Received from server: %s\n", received_data); free(received_data);