Created
February 23, 2023 08:06
-
-
Save airvzxf/a62f4aee29e0a23b12d02161115c88ca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/socket.h> // For socket functions | |
#include <netinet/in.h> // For sockaddr_in | |
#include <cstdlib> // For exit() and EXIT_FAILURE | |
#include <iostream> // For cout | |
#include <unistd.h> // For read | |
// Compile: `g++ main.cpp -o web-service-c` | |
// Usage: `telnet localhost 8002` | |
int main() { | |
// Create a socket (IPv4, TCP) | |
int sockfd = socket(AF_INET, SOCK_STREAM, 0); | |
if (sockfd == -1) { | |
std::cout << "Failed to create socket. errno: " << errno << std::endl; | |
exit(EXIT_FAILURE); | |
} | |
// Listen to port 8002 on any address | |
sockaddr_in sockaddr; | |
sockaddr.sin_family = AF_INET; | |
sockaddr.sin_addr.s_addr = INADDR_ANY; | |
sockaddr.sin_port = htons(8002); | |
if (bind(sockfd, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) < 0) { | |
std::cout << "Failed to bind to port 8002. errno: " << errno << std::endl; | |
exit(EXIT_FAILURE); | |
} | |
// Start listening. Hold at most 10 connections in the queue | |
if (listen(sockfd, 10) < 0) { | |
std::cout << "Failed to listen on socket. errno: " << errno << std::endl; | |
exit(EXIT_FAILURE); | |
} | |
// Grab a connection from the queue | |
auto addrlen = sizeof(sockaddr); | |
int connection = accept(sockfd, (struct sockaddr*)&sockaddr, (socklen_t*)&addrlen); | |
if (connection < 0) { | |
std::cout << "Failed to grab connection. errno: " << errno << std::endl; | |
exit(EXIT_FAILURE); | |
} | |
// Read from the connection | |
char buffer[100]; | |
auto bytesRead = read(connection, buffer, 100); | |
std::cout << "The message was: " << buffer; | |
// Send a message to the connection | |
std::string response = "Good talking to you\n"; | |
send(connection, response.c_str(), response.size(), 0); | |
// Close the connections | |
close(connection); | |
close(sockfd); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment