send a message to the client

This commit is contained in:
ktyl 2023-02-17 21:06:55 +00:00
parent 3c3f315426
commit 8b62cd574d
2 changed files with 50 additions and 19 deletions

View File

@ -125,11 +125,28 @@ void error(const char* message)
exit(1); 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; int newsockfd;
struct sockaddr_in serv_addr, cli_addr; struct sockaddr_in cli_addr;
socklen_t clilen; 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 // open socket and await connection from client
sockfd = socket(AF_INET, SOCK_STREAM, 0); sockfd = socket(AF_INET, SOCK_STREAM, 0);
@ -153,27 +170,40 @@ void wait_for_client()
// successfully bound socket, start listening for connections // successfully bound socket, start listening for connections
listen(sockfd, 5); listen(sockfd, 5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr*)&cli_addr, &clilen); newsockfd = accept_client(sockfd);
if (newsockfd < 0) 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("SEND %s\n", message);
printf("got a connection!\n");
// close sockets we opened
close(newsockfd);
close(sockfd);
// once connection is acquired, exit
exit(0);
} }
int main() 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"; std::cout << "P3\n" << WIDTH << ' ' << HEIGHT << "\n255\n";

View File

@ -2,9 +2,10 @@ fantasy telescope idea
use rti1w as a base use rti1w as a base
* [ ] move rendering out of main.cpp
* [x] server waits for connection * [x] server waits for connection
* [x] client establishes connection * [x] client establishes connection
* [x] send a message to the client
* [ ] move rendering out of main.cpp
* [ ] send rendered image data to client * [ ] send rendered image data to client
* [ ] form image file on client * [ ] form image file on client
* [ ] client sends receiving port to server * [ ] client sends receiving port to server