04_intro_to_sockets: split communicate in tcp_write and tcp_read

This commit is contained in:
Daniel Meiburg 2024-05-17 12:48:00 +02:00
parent c787162c82
commit fe43eafb5c
Signed by: dm
GPG Key ID: E5827ECFFE0AA4F2
3 changed files with 9 additions and 6 deletions

View File

@ -13,7 +13,6 @@ static void error_handling(char *message, int sock) {
perror(message); perror(message);
if (sock != -1) if (sock != -1)
close(sock); close(sock);
close(sock);
} }
int tcp_create_socket() { int tcp_create_socket() {
@ -39,12 +38,14 @@ void connect_to_server(int sock, char *ip, int port) {
error_handling("connect() error", sock); error_handling("connect() error", sock);
} }
char* communicate(int sock, char *message) { int tcp_write(int sock, char* message) {
// Sending the ASCII string // Sending the ASCII string
if (write(sock, message, strlen(message)) == -1) if (write(sock, message, strlen(message)) == -1)
error_handling("write() error", sock); error_handling("write() error", sock);
return 0;
}
// Receiving response char *tcp_read(int sock) {
char* response = malloc(BUFFER_SIZE); char* response = malloc(BUFFER_SIZE);
if (!response) if (!response)
error_handling("Failed to allocate memory for response", sock); error_handling("Failed to allocate memory for response", sock);

View File

@ -7,8 +7,9 @@ int tcp_create_socket();
// Function to connect to a server // Function to connect to a server
void connect_to_server(int sock, char *ip, int port); void connect_to_server(int sock, char *ip, int port);
// Function to communicate with the server int tcp_write(int sock, char* message);
char* communicate(int sock, char *message);
char *tcp_read(int sock);
// Function to create a TCP server socket // Function to create a TCP server socket
int tcp_listen(int port); int tcp_listen(int port);

View File

@ -11,7 +11,8 @@ int main(int argc, char *argv[]) {
int sock = tcp_create_socket(); int sock = tcp_create_socket();
connect_to_server(sock, argv[1], atoi(argv[2])); 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) { if (received_data) {
printf("Received from server: %s\n", received_data); printf("Received from server: %s\n", received_data);
free(received_data); free(received_data);