windows socket 数据简单结构化
Posted xuqiulin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了windows socket 数据简单结构化相关的知识,希望对你有一定的参考价值。
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 数据简单结构化的主要内容,如果未能解决你的问题,请参考以下文章
为啥 std::mutex 在带有 WIndows SOCKET 的结构中使用时会创建 C2248?