TCP Socket FIONREAD仅在每次recv调用linux时递增

时间:2015-07-06 21:08:09

标签: linux tcpsocket

我有一个服务器客户端设置,当服务器fd有数据要读取时,运行回调来格式化和传播数据。服务器和客户端共享定义有效负载的相同标头,如下所示:

#ifndef DATA_HEADER_
#define DATA_HEADER_

#pragma pack(1)

typedef struct {
  int command;
  uint8_t val;
} cmd_t;

#pragma pack()

#endif

执行读取的回调函数如下:

int Server::onBytesAvailable(Socket *s)
{
  //get bytes available and set up data array
  int len = s->bytesAvailable();
  char *msg = new char[len];
  s->read(msg, len);

  //cast as command struct
  cmd_t *cmd = (cmd_t *) msg;

  //print values
  std::cout << "LEN: " << len << std::endl;
  std::cout << "MSG LEN " << sizeof(msg) << std::endl;
  std::cout << "CMD: " << cmd->cmdid << std::endl;
  std::cout << "VAL: " << cmd->togglePwr << std::endl;

  propigateData(cmd);
  return 0;
}

bytesAvailable()调用运行ioctl(fd,FIONREAD和&amp; size)以获取可从套接字读取的字节数。每当运行回调时,bytesAvailable()只会继续增加5,并且有效负载中的数据值只是垃圾。读取调用在fd上运行recv并将数据放入msg数组中。

打印输出如下所示:

output:

LEN: 5
MSG LEN 4
CMD: 0
VAL: ▒
LEN: 10
MSG LEN 4
CMD: 0
VAL: ▒
LEN: 15
MSG LEN 4
CMD: 0
VAL:
LEN: 20
MSG LEN 4
CMD: 0
VAL:

我是套接字的新手,所以非常感谢任何帮助!

0 个答案:

没有答案