From 8b62cd574de59308e28aa3b71de66d16e81569e0 Mon Sep 17 00:00:00 2001 From: ktyl Date: Fri, 17 Feb 2023 21:06:55 +0000 Subject: [PATCH] send a message to the client --- src/main.cpp | 66 ++++++++++++++++++++++++++++++++++++++-------------- telescope.md | 3 ++- 2 files changed, 50 insertions(+), 19 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 443e17e..b1c16cf 100755 --- a/src/main.cpp +++ b/src/main.cpp @@ -125,11 +125,28 @@ void error(const char* message) exit(1); } -void wait_for_client() +// file descriptor of the socket we're listening for connections on +// +// returns fd for the client connection +int accept_client(int sockfd) { - int sockfd, newsockfd; - struct sockaddr_in serv_addr, cli_addr; - socklen_t clilen; + int newsockfd; + struct sockaddr_in cli_addr; + socklen_t clilen = sizeof(cli_addr); + + newsockfd = accept(sockfd, (struct sockaddr*)&cli_addr, &clilen); + if (newsockfd < 0) + { + error("ERROR accepting client"); + } + + return newsockfd; +} + +int wait_for_client(int& sockfd) +{ + int newsockfd; + struct sockaddr_in serv_addr; // open socket and await connection from client sockfd = socket(AF_INET, SOCK_STREAM, 0); @@ -153,27 +170,40 @@ void wait_for_client() // successfully bound socket, start listening for connections listen(sockfd, 5); - clilen = sizeof(cli_addr); - newsockfd = accept(sockfd, (struct sockaddr*)&cli_addr, &clilen); - if (newsockfd < 0) + newsockfd = accept_client(sockfd); + return newsockfd; +} + +void send_message(int sock, const char* message) +{ + int written = write(sock, message, strlen(message)); + if (written < 0) { - error("ERROR accepting client"); + error("ERROR sending message to the client"); } - - printf("got a connection!\n"); - - // close sockets we opened - close(newsockfd); - close(sockfd); - - // once connection is acquired, exit - exit(0); + printf("SEND %s\n", message); } int main() { - wait_for_client(); + int sockfd; + int newsockfd = wait_for_client(sockfd); + + printf("got a connection!\n"); + + // write a message to the client + send_message(newsockfd, "hi there!"); + + // close client socket + close(newsockfd); + + printf("closed client connection\n"); + + // close listening socket + close(sockfd); + // exit after all our connections are closed + exit(0); std::cout << "P3\n" << WIDTH << ' ' << HEIGHT << "\n255\n"; diff --git a/telescope.md b/telescope.md index 0b5569e..3574d23 100644 --- a/telescope.md +++ b/telescope.md @@ -2,9 +2,10 @@ fantasy telescope idea use rti1w as a base -* [ ] move rendering out of main.cpp * [x] server waits for connection * [x] client establishes connection +* [x] send a message to the client +* [ ] move rendering out of main.cpp * [ ] send rendered image data to client * [ ] form image file on client * [ ] client sends receiving port to server