码迷,mamicode.com
首页 > Windows程序 > 详细

windows socket 数据简单结构化

时间:2019-08-31 01:09:29      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:bsp   int   null   %s   pac   cep   ini   erro   ons   

client

struct DataPackage {
    int age;
    char name[32];
};
//结构化的网络消息
int function07() {
    SOCKET sktCli = init("192.168.3.18", 8080);
    if (sktCli == INVALID_SOCKET) {
        return -1;
    }

    while (true) {
        printMenu();
        char szCmd[64] = { 0 };
        scanf("%s", szCmd);
        if (strcmp(szCmd, "exit") == 0) {
            printf("[client] exit ...\n");
            break;
        }
        send(sktCli, szCmd, strlen(szCmd) + 1, 0);

        char szRecv[1024] = { 0 };
        int ret = recv(sktCli, szRecv, sizeof(szRecv), 0);
        if (ret <= 0) {
            printf("[client] server exit ...\n");
            break;
        }
        DataPackage *p = (DataPackage*)szRecv;
        printf("[server] msg: age=%d name=%s\n", p->age, p->name);
    }

    destroy(sktCli);
    return 0;
}

server

struct DataPackage {
    int age;
    char name[32];
};

//结构化的网络消息
int function07() {
    SOCKET sktServ = init("0.0.0.0", 8080);
    if (sktServ == INVALID_SOCKET) {
        return -1;
    }

    SOCKET sktCli = accept(sktServ, NULL, NULL);
    while (true) {
        char szCmd[64] = { 0 };
        int ret = recv(sktCli, szCmd, sizeof(szCmd), 0);
        if (ret == SOCKET_ERROR) {
            printf("[server] recv error ...\n");
            break;
        }
        if (ret == 0) {
            printf("[client] exit ...\n");
            break;
        }
        printf("[client] %s\n", szCmd);
        char szMsg[1024];
        if (strcmp(szCmd, "getInfo") == 0) {
            DataPackage dp = {1000, "爱白菜的小昆虫"};
            send(sktCli, (const char *)&dp, sizeof(dp), 0);
        }
        else {
            sprintf(szMsg, "%s", "???.");
            send(sktCli, szMsg, strlen(szMsg) + 1, 0);
        }
    }

    destroy(sktServ);
    return 0;
}

 

windows socket 数据简单结构化

标签:bsp   int   null   %s   pac   cep   ini   erro   ons   

原文地址:https://www.cnblogs.com/xuqiulin/p/11437589.html

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