在winsock2中发送其他数据类型
winsock2 中的发送函数仅接受字符指针。 如何通过它发送整数或对象?
The send function in winsock2 accepts only char pointers.
How do I send integers or objects through it too?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要作为参数传递给
send()
函数的const char *buf
只是一个指向字节数组的指针。您需要将整数转换为字节:并读取代码:
并且复杂对象需要序列化为字节流。
注 1:如果服务器和客户端使用相同的平台 (x32 / x64 / ...),则代码示例有效,这意味着
int
具有相同的字节数且字节顺序相同。注 2:编写代码时应检查每一步是否有缓冲区 (
MAX_BUF_SIZE
) 溢出。const char *buf
which you need to pass tosend()
function as an argument is just a pointer to array of bytes. You need to convert integers to bytes:and reading code:
and complex objects needs to be serialized to stream of bytes.
Note 1: The code sample is valid iff both server and client use the same platforms (x32 / x64 / ...) that means
int
has the same amount of bytes and byte order is the same.Note 2: Writing code should check that there is no buffer (
MAX_BUF_SIZE
) overflow on each step.只需将值存储到变量中,然后将变量类型转换为 char* 即可。
send()
和recv()
函数对二进制数据进行操作,尽管采用char*
参数。发送:
阅读:
Just store the value into a variable and then type-cast the variable to
char*
. Thesend()
andrecv()
functions operate on binary data, despite takingchar*
parameters.Sending:
Reading:
通常,最简单的方法是将整数或对象打印到字符串,然后发送该字符串。文本表示更易于移植,也更易于调试。
std::stringstream
可能是一个有用的类,既可以创建字符串,也可以在另一端解析它。Generally, the easiest way is to print the integer or object to a string, and send that string. Textual representations are more portable, and also easier to debug.
std::stringstream
may be a useful class both to create the string and parse it on the other end.