Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.9 kB
1
Indexable
Never
#include <iostream>
#include <winsock2.h>

#pragma comment(lib, "ws2_32.lib") // Link with ws2_32.lib

int main() {
    // Initialize Winsock
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        std::cout << "Failed to initialize Winsock.\n";
        return 1;
    }

    // Create a socket
    SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket == INVALID_SOCKET) {
        std::cout << "Failed to create socket.\n";
        WSACleanup();
        return 1;
    }

    // Bind the socket to an IP address and port
    sockaddr_in serverAddress{};
    serverAddress.sin_family = AF_INET;
    serverAddress.sin_port = htons(1234); // Choose a port number
    serverAddress.sin_addr.s_addr = INADDR_ANY; // Bind to all available interfaces

    if (bind(serverSocket, reinterpret_cast<sockaddr*>(&serverAddress), sizeof(serverAddress)) == SOCKET_ERROR) {
        std::cout << "Failed to bind socket.\n";
        closesocket(serverSocket);
        WSACleanup();
        return 1;
    }

    // Listen for incoming connections
    if (listen(serverSocket, SOMAXCONN) == SOCKET_ERROR) {
        std::cout << "Failed to listen on socket.\n";
        closesocket(serverSocket);
        WSACleanup();
        return 1;
    }

    std::cout << "Server listening on port 1234...\n";

    // Accept a client connection
    sockaddr_in clientAddress{};
    int clientAddressSize = sizeof(clientAddress);
    SOCKET clientSocket = accept(serverSocket, reinterpret_cast<sockaddr*>(&clientAddress), &clientAddressSize);
    if (clientSocket == INVALID_SOCKET) {
        std::cout << "Failed to accept client connection.\n";
        closesocket(serverSocket);
        WSACleanup();
        return 1;
    }

    // Communication with the client
    std::cout << "Client connected.\n";

    // Receive data from the client
    char buffer[1024];
    int bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0);
    if (bytesRead == SOCKET_ERROR) {
        std::cout << "Failed to receive data from client.\n";
        closesocket(clientSocket);
        closesocket(serverSocket);
        WSACleanup();
        return 1;
    }

    std::cout << "Received data from client: " << buffer << "\n";

    // Send a response back to the client
    const char* response = "Hello from C++ server!";
    int bytesSent = send(clientSocket, response, strlen(response), 0);
    if (bytesSent == SOCKET_ERROR) {
        std::cout << "Failed to send response to client.\n";
        closesocket(clientSocket);
        closesocket(serverSocket);
        WSACleanup();
        return 1;
    }

    std::cout << "Response sent to client.\n";

    // Clean up
    closesocket(clientSocket);
    closesocket(serverSocket);
    WSACleanup();

    return 0;
}