#include #include #include #include #include #include #include #include #include int main(int argc, char **argv) { int ssock, csock, i; static char buff[256]; ssize_t nbytes; struct sockaddr_in saddr; memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = htons(6666); signal(SIGPIPE, SIG_IGN); printf("Server started...\n"); if ((ssock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("socket() error. (%d) %s\n", errno, strerror(errno)); exit(1); } printf("Created SOCK_STREAM socket\n"); if (bind(ssock, (struct sockaddr*)&saddr, sizeof(saddr)) == -1) { printf("bind() error. (%d) %s\n", errno, strerror(errno)); close(ssock); exit(1); } printf("Bound to localhost:6666\n"); if (listen(ssock, 1) == -1) { printf("listen() error. (%d) %s\n", errno, strerror(errno)); close(ssock); exit(1); } printf("waiting for connection...\n"); csock = accept(ssock, NULL, NULL); if (csock == -1) { printf("accept() error. (%d) %s\n", errno, strerror(errno)); close(ssock); exit(1); } printf("Client connected!\n"); printf("Waiting for some data from client\n"); while ((nbytes = recv(csock, buff, sizeof(buff), 0)) > 0) { printf("Received: \"%s\"\n", buff); } if (nbytes < 0) { printf("recv() error. (%d) %s\n", errno, strerror(errno)); close(ssock); close(csock); exit(1); } else if (nbytes == 0) { printf("Received EOF\n"); printf("Sending msg to client: \"MSG from server\"\n"); if ((nbytes = send(csock, "MSG from server", sizeof("MSG from server"), 0)) <= 0) { printf("send() error. (%d) %s\n", errno, strerror(errno)); close(ssock); close(csock); exit(1); } } printf("sleep(5)\n"); sleep(5); i = 1; while (1) { printf("Sending %d msg to client: \"MSG from server\"\n", i); nbytes = send(csock, "MSG from server", sizeof("MSG from server"), 0); printf("try #%d send() result: (%d) %s\n",i ,errno, strerror(errno)); if (nbytes <= 0) break; ++i; } printf("Server exiting...\n"); close(ssock); close(csock); return 0; }