diff options
Diffstat (limited to 'server.c')
-rw-r--r-- | server.c | 37 |
1 files changed, 34 insertions, 3 deletions
@@ -1,11 +1,20 @@ #include <netinet/in.h> #include <sys/socket.h> #include <arpa/inet.h> -#include <string.h> +#include <strings.h> +#include <stdlib.h> +#include <stdbool.h> +#include <stdio.h> +#include <sys/types.h> +#include <unistd.h> + +#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,14 +22,36 @@ int main() serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); serv_addr.sin_port = htons(8888); - bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)); + if (bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -1) + panic("socket bind error"); - listen(sockfd, SOMAXCONN); + if (listen(sockfd, SOMAXCONN) == -1) + panic("socket listen error"); struct sockaddr_in clnt_addr; socklen_t clnt_addr_len = sizeof(clnt_addr); bzero(&clnt_addr, sizeof(clnt_addr)); + int clnt_sockfd = accept(sockfd, (struct sockaddr *)&clnt_addr, &clnt_addr_len); + if (clnt_sockfd == -1) + panic("socket accept error"); printf("New client fd %d, ip: %s, port: %d\n", clnt_sockfd, inet_ntoa(clnt_addr.sin_addr), ntohs(clnt_addr.sin_port)); + + while (true) { + char buf[1024]; + bzero(&buf, sizeof(buf)); + ssize_t n_read_bytes = read(clnt_sockfd, buf, sizeof(buf)); + if (n_read_bytes > 0) { + printf("message from client fd %d: %s\n", clnt_sockfd, buf); + write(clnt_sockfd, buf, sizeof(buf)); + } else if (n_read_bytes == 0) { + printf("client fd %d disconnected\n", clnt_sockfd); + close(clnt_sockfd); + break; + } else if (n_read_bytes == -1) { + close(clnt_sockfd); + panic("socket read error"); + } + } } |