-1

对不起,我的英语不好。

上下文 :

我有 6 个变量

  1. 无符号的字符
  2. 字符
  3. 无符号短
  4. 整数
  5. 整数
  6. 整数

我序列化这些数据以准备发送到套接字。

问题,我怎样才能存储我的序列化数据并发送它?

我的第一个解决方案是使用一个结构来发送我的数据,但是这个解决方案需要强制转换并且强制转换操作非常慢。

您有比将我的变量存储在结构中更好的解决方案吗?

#include <sstream>
#include <string.h>

typedef int SOCKET;
typedef struct sockaddr_in SOCKADDR_IN;
typedef struct sockaddr SOCKADDR;

#define PORT 4241
template<typename T>
inline std::ostream& raw_write(std::ostream &os, const T &t)
{
  return os.write( reinterpret_cast<const char*>(&t), sizeof t);
}

int main()
{
  char protocole;
  char id_module;
  unsigned short id_message;
  int id_client;
  int size_msg;
  unsigned long timestamp;

  SOCKET csock;
  SOCKADDR_IN csin;

  protocole = 1;
  id_module = 2;
  id_message = 256;
  id_client = 8569;
  size_msg = 145;
  timestamp = 1353793384;
  csock = socket(AF_INET, SOCK_STREAM, 0);
  csin.sin_addr.s_addr = inet_addr("127.0.0.1");
  csin.sin_family = AF_INET;
  csin.sin_port = htons(PORT);
  connect(csock, (SOCKADDR*)&csin, sizeof(csin));
  raw_write(ss, protocole);
  raw_write(ss, id_module);
  raw_write(ss, id_message);
  raw_write(ss, id_client);
  send(csock, ss.str().c_str(), strlen(ss.str().c_str()), 0);
  close(csock);

}

不起作用,因为字符串包含 '\0' 并发送剪切它。

我说,在许多数据发送上,cast 很慢。在接收时,我需要再次投射以恢复我的数据。

此操作比仅读取字节更慢。

4

1 回答 1

2

I f you dont want to do it from scratch, you could use Google Protocol Buffers. Its a strong library letting you define a protocol, which is nothing else but a class, that can (de)serialize itself to(from) a stream, file, buffer or string.

I use it myself, its nice to serialze it to a string which is easy to send via socket.

EDIT: Reply to comment:

Okay then notice that its not send (...) truncating your stream. Its c_str() which ends on a '\0'. Maybe you should try to avoid streams and use a container which offers access to its raw data like std::string or std::vector with const void * data(). You could pass this and size() to send(...).

于 2012-11-28T09:49:43.677 回答