From 122a69f715acfe73963a2347cbb335e41bce944c Mon Sep 17 00:00:00 2001 From: Guangxiong Lin Date: Thu, 1 Dec 2022 16:08:38 +0800 Subject: Implement echo server with error handling Implement echo server with error handling Fix gitignore Implement an echo server with error handling --- client.c | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) (limited to 'client.c') diff --git a/client.c b/client.c index 82c35a6..9e3a421 100644 --- a/client.c +++ b/client.c @@ -1,11 +1,19 @@ #include #include #include +#include +#include +#include +#include + +#include "common.h" int main() { int sockfd = socket(AF_INET, SOCK_STREAM, 0); + if (sockfd == -1) + panic("socket creation error"); struct sockaddr_in serv_addr; bzero(&serv_addr, sizeof(serv_addr)); @@ -13,5 +21,28 @@ main() serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); serv_addr.sin_port = htons(8888); - connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); + if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1) + panic("socket connect error"); + + while (true) { + char buf[1024]; + bzero(&buf, sizeof(buf)); + scanf("%s", buf); + ssize_t n_write_bytes = write(sockfd, buf, sizeof(buf)); + if (n_write_bytes == -1) { + printf("socket already disconnected, cannot write any more!\n"); + break; + } + + ssize_t n_read_bytes = read(sockfd, buf, sizeof(buf)); + if (n_read_bytes > 0) { + printf("message from server: %s\n", buf); + } else if (n_read_bytes == 0) { + printf("server socket disconnected!\n"); + break; + } else if (n_read_bytes == -1) { + close(sockfd); + panic("socket read error"); + } + } } -- cgit v1.2.3