码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-04-05 22:39:02      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:sock   ddr   return   stream   printf   pause   eof   套接字   orm   

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;
}

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

标签:sock   ddr   return   stream   printf   pause   eof   套接字   orm   

原文地址:https://www.cnblogs.com/1625--H/p/12639288.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!