从C scoket发送/ recv的缓冲类型 [英] C sockets send/recv buffer type

查看:108
本文介绍了从C scoket发送/ recv的缓冲类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与Unix套接字的工作,我可以发送(),当我的缓冲区是char类型的recv()数据(即发送和接收字符串)。我用Beej的指南,插座,以及使用的例子是为send'ing / recv'ing字符串。

I'm working with unix sockets, and I can send() and recv() data when my buffer is of type char (ie. sending and receiving strings). I used Beej's guide to sockets, and the examples used were for send'ing/recv'ing strings.

现在我想在一个消息发送不同类型的/ recv的数据。结果
例如,假设在一个消息我想送一个整数,字符串,一张双人床和一个浮动。
我应该如何去这样做呢?更具体地说,什么类型应我的消息缓冲区是什么?

Now I want to send/recv data of different types in one message.
For example, say in one message I want to send an integer, a string, a double and a float. How should I go about doing this? More specifically, of what type should my message 'buffer' be?

有关send和recv原型:

The prototypes for send and recv:

int recv (int socket, void *buffer, size_t size, int flags)
int send (int socket, void *buffer, size_t size, int flags)

我没有用C / C ++和指针太多的经验,所以这可能是一个noob问题。

I don't have too much experience with C/C++ and pointers, so this is probably a noob question.

如果任何人都可以指导我在正确的方向,我真的AP preciate它。
谢谢

If anyone can guide me in the right direction, I'd really appreciate it. Thanks

推荐答案

除非你打算发送大量数据(很多千字节)和经常(每秒几个数据包),我建议您翻译的数据串(又名序列化数据),并通过这种方式。它有几个好处:

Unless you are planning to send vast amounts of data (many kilobytes) and often (several packets per second), I would suggest that you translate your data to strings (aka "serialize the data") and pass it that way. It has several benefits:


  1. 这是便携式 - 作品不管是什么尺寸的 INT 浮动是 - 或字段之间的填充是在结构的东西。

  2. 这很容易调试(你可以看一下数据,说无论是对还是错)

  3. 没关系的发送/接收设备是什么字节顺序。

  1. It's portable - works no matter what size an int or float or double is - or what the padding between fields are in the structure.
  2. It's easy to debug (you can just look at the data and say whether it is right or wrong)
  3. It doesn't matter what byte-order the sending/receiving machines are.

发送二进制数据,另一方面是复杂的,因为你需要担心的数据字段的个体大小和内部重新presentation(字节顺序,怎一个双击在结构中的数据字段的二进制,填充psnted重新$ p $,不能通过指针,等等等等)。唯一的好处是,二进制数据是一个小更紧凑。但是,只有事项如果你有很多千字节和/或发送大量数据包的每一秒。

Sending binary data, on the other hand is complex, because you need to worry about the individual sizes of data fields and their internal representation (byte order, how a double is represnted in binary, padding of data fields within structures, can't pass pointers, etc, etc). The only benefit is that binary data is a little more compact. But that only matters if you have many kilobytes and/or send lots of packets every second.

这篇关于从C scoket发送/ recv的缓冲类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆