write some Modern C++20 that reads from a socket
- User
write some Modern C++20 that reads from a socket
Assistant
Here's an example of reading from a socket using modern C++20 with the
std::socketlibrary:#include <iostream> #include <string> #include <cstring> // for memset #include <cstdlib> // for atoi #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <cstring> int main() { int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { std::cerr << "Failed to create socket" << std::endl; return 1; } struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(8080); addr.sin_addr.s_addr = inet_addr("127.0.0.1"); if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { std::cerr << "Failed to connect to the server" << std::endl; return 1; } std::string message = "Hello, server!"; send(sock, message.c_str(), message.length(), 0); char buffer[1024] = {}; int bytes_received = recv(sock, buffer, sizeof(buffer), 0); if (bytes_received < 0) { std::cerr << "Failed to receive data" << std::endl; return 1; } buffer[bytes_received] = '\0'; std::cout << "Received: " << buffer << std::endl; close(sock); return 0; }In this example, the program creates a socket using the
socketfunction, connects to the server using theconnectfunction,
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.