vc++实现的tcp socket客户端和服务端示例


当然,我可以为你提供VC++中使用WinSock API实现的TCP Socket客户端和服务端的示例代码。这里我将分两部分给出:客户端和服务端。

### TCP Socket 服务端示例(C++ 使用 WinSock)


#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")

#define PORT 8080

int main() {
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);

    SOCKET ListenSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (ListenSocket == INVALID_SOCKET) {
        std::cerr << "Socket creation failed" << std::endl;
        return -1;
    }

    sockaddr_in service;
    service.sin_family = AF_INET;
    service.sin_addr.s_addr = INADDR_ANY;
    service.sin_port = htons(PORT);

    if (bind(ListenSocket, (SOCKADDR*)&service, sizeof(service)) == SOCKET_ERROR) {
        std::cerr << "Bind failed" << std::endl;
        return -1;
    }

    if (listen(ListenSocket, 5) == SOCKET_ERROR) {
        std::cerr << "Listen failed" << std::endl;
        return -1;
    }

    SOCKET ClientSocket;
    sockaddr_in client;
    int clientSize = sizeof(client);
    ClientSocket = accept(ListenSocket, (SOCKADDR*)&client, &clientSize);
    if (ClientSocket == INVALID_SOCKET) {
        std::cerr << "Accept failed" << std::endl;
        return -1;
    }

    // 假设这里只是简单地发送一个消息
    const char* message = "Hello from server!";
    send(ClientSocket, message, strlen(message), 0);

    closesocket(ClientSocket);
    closesocket(ListenSocket);
    WSACleanup();

    return 0;
}

### TCP Socket 客户端示例(C++ 使用 WinSock)


#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")

#define PORT 8080

int main() {
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);

    SOCKET Socket = socket(AF_INET, SOCK_STREAM, 0);
    if (Socket == INVALID_SOCKET) {
        std::cerr << "Socket creation failed" << std::endl;
        return -1;
    }

    sockaddr_in service;
    service.sin_family = AF_INET;
    service.sin_addr.s_addr = inet_addr("127.0.0.1");
    service.sin_port = htons(PORT);

    if (connect(Socket, (SOCKADDR*)&service, sizeof(service)) == SOCKET_ERROR) {
        std::cerr << "Connection failed" << std::endl;
        return -1;
    }

    char buffer[1024];
    int bytesReceived = recv(Socket, buffer, 1024, 0);
    if (bytesReceived == SOCKET_ERROR) {
        std::cerr << "Recv failed" << std::endl;
        return -1;
    }

    buffer[bytesReceived] = '\0';
    std::cout << "Message from server: " << buffer << std::endl;

    closesocket(Socket);
    WSACleanup();

    return 0;
}

这两个示例分别展示了如何在VC++中使用WinSock API创建一个TCP Socket服务端和一个TCP Socket客户端。服务端监听一个端口,接受客户端的连接,并向客户端发送一条消息。客户端连接到服务端,接收并打印服务端发送的消息。请注意,你需要确保你的开发环境已经配置了WinSock库。