C++ Socket 入门——回声客户端

Server端:

#include <stdio.h>
#include <winsock2.h>
#pragma comment (lib, "ws2_32.lib")  //加载 ws2_32.dll
#define BUF_SIZE 100

int main() {

    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);

    //创建套接字
    SOCKET servSock = socket(AF_INET, SOCK_STREAM, 0);

    //绑定套接字
    sockaddr_in sockAddr;
    memset(&sockAddr, 0, sizeof(sockAddr));  //每个字节都用0填充
    sockAddr.sin_family = PF_INET;  //使用IPv4地址
    sockAddr.sin_addr.s_addr = inet_addr("127.0.0.1");  //具体的IP地址
    sockAddr.sin_port = htons(1234);  //端口

    bind(servSock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR));

    //进入监听状态
    listen(servSock, 20);

    //接收客户端请求
    SOCKADDR clntAddr;
    int nSize = sizeof(SOCKADDR);
    SOCKET clntSock = accept(servSock, (SOCKADDR*)&clntAddr, &nSize);

    while (true) {
        char buffer[BUF_SIZE];
        int strLen = recv(clntSock, buffer, BUF_SIZE, 0);
        buffer[strLen] = '\0';
        if (strcmp(buffer, "quit") == 0) break;
        send(clntSock, buffer, strLen, 0);
    }

    //关闭套接字
    closesocket(clntSock);
    closesocket(servSock);
    //终止 DLL 的使用
    WSACleanup();
    return 0;
}

Client 端

#include <stdio.h>
#include <stdlib.h>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")  //加载 ws2_32.dll

#define BUF_SIZE 100

int main() {
    //初始化DLL    Windows Socket API DATA
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);


    //创建套接字
    SOCKET sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

    //向服务器发起请求
    sockaddr_in sockAddr;

    memset(&sockAddr, 0, sizeof(sockAddr));  //每个字节都用0填充
    sockAddr.sin_family = PF_INET;
    sockAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    sockAddr.sin_port = htons(1234);
    connect(sock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR));

    while (true) {
        char bufSend[BUF_SIZE] = { 0 };
        printf("Input a string: ");
        scanf("%s", bufSend);
        send(sock, bufSend, strlen(bufSend), 0);
        if (strcmp(bufSend, "quit") == 0) {
            break;
        }
        char bufRecv[BUF_SIZE] = { 0 };
        recv(sock, bufRecv, BUF_SIZE, 0);

        //输出接收到的数据
        printf("Message form server: %s\n", bufRecv);
    }

    //关闭套接字
    closesocket(sock);

    //终止使用 DLL 
    WSACleanup();

    system("pause");
    return 0;
}
上一篇:从sockaddr结构获取IP和端口


下一篇:java day1