From 459123928ab5eb8fa3994a7d812ee9ec5838c0f2 Mon Sep 17 00:00:00 2001 From: Niklas Halle Date: Thu, 28 May 2020 13:59:46 +0200 Subject: erstes gedöns MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 03_exercise/cli/client.c | 67 +++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 61 insertions(+), 6 deletions(-) (limited to '03_exercise/cli') diff --git a/03_exercise/cli/client.c b/03_exercise/cli/client.c index 48bf724..3cd6f1b 100644 --- a/03_exercise/cli/client.c +++ b/03_exercise/cli/client.c @@ -1,13 +1,68 @@ #include +#include #include +#include +#include +#include +#include + #define PORT 9000 #define HOST "127.0.0.1" -int main() -{ - getc(stdin); - printf("Client Exit\n"); - - return 0; +static inline void die(const char *msg) { + perror(msg); + exit(-1); +} + +int main() { + struct sockaddr_in addr = { + .sin_family = AF_INET, + .sin_port = htons(PORT), + .sin_addr.s_addr = inet_addr(HOST) + }; + char buf[256]; + int cfd; + + if ((cfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) + die("Could not open socket"); + + if (connect(cfd, (struct sockaddr *) &addr, sizeof(addr)) < 0) + die("Could not connect to socket"); + + char *line = NULL; + size_t cap = 0; + __ssize_t length; + + while (1) { + if ((length = getline(&line, &cap, stdin)) < 0) { + fprintf(stderr, "Failed to read from STDIN"); + fflush(stderr); + exit(-1); + } + + if (strspn(line, " \n\t") == strlen(line)) { + // skip empty lines - empty being just spaces or tabs + continue; + } + + line[length - 1] = '\0'; // cut the line feed + + if (strcmp(line, "exit") == 0) { + break; + } + + strncpy(buf, line, strlen(line)); + + if (write(cfd, buf, sizeof(buf)) < 0) + die("Could not send message"); + + if (read(cfd, buf, sizeof(buf)) < 0) + die("Could not receive message"); + + printf("$> %s\n", buf); + } + + close(cfd); + return 0; } -- cgit v1.2.3-54-g00ecf