我有一个服务器客户端设置,当服务器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:
我是套接字的新手,所以非常感谢任何帮助!