我一直在研究 winsock,我想创建一个小游戏来测试它。现在我想到了一个客户端/服务器系统,所以我需要客户端将数据发送到服务器。
我可以发送 char* 数据(就像发送函数想要的那样),但我不知道如何将带有数据的结构发送到另一台计算机。 我读到我需要使用序列化,但这似乎写入文件,我不需要它。 所以,我需要的是该结构可以通过 winsock 发送,并且可以在服务器上重建,反之亦然。
有人可以帮助我理解这个问题吗?感谢您的帮助。
编辑: 以下是否足够?
tester test;
test.pos = 10;
send(sock, (char*)&test, (int)strlen(test), 0);
更多编辑:
这就是现在可以作为测试使用的方法。这是一个好方法吗?
tester test;
test.pos = 350;
char* buffer = (char*)&test;
tester* testFollowup = (tester*)buffer;
cout << (int)testFollowup->pos;
getchar();
return 0;
最佳答案
我强烈建议您在开始时使用一个库来为您处理这个问题——一个很好的、轻量级的例子是 Protocol Buffers ,由 Google 设计的序列化协议(protocol)。
Protocol buffers are a flexible, efficient, automated mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages. You can even update your data structure without breaking deployed programs that are compiled against the "old" format.
如果 Google Protocol Buffers 不适合您,请随时 keep looking around ,我相信您会找到可以使用的东西:)
关于c++ - 如何通过 winsock 发送自定义数据(可能是来自指针的数据),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23155585/