我正在建立MQTT经纪人。
所以,当我从客户端收到MQTT数据包时。该数据包也在同时发送。我找不到原因。我在下面发布我的代码片段请指出我哪里出错了。
static void onServEcho(struct bufferevent* bev, void* cbarg) {
EvBufferEvent evbuf(bev);
struct evbuffer *input = bufferevent_get_input(bev);
struct evbuffer *output = bufferevent_get_output(bev);
size_t len = evbuffer_get_length(input);
evutil_socket_t accept_fd = bufferevent_getfd(bev);
// Copy all the data from the input buffer to the output buffer.
char *data;
//data =(char *) malloc(len);
data = new char[len];
// cout<<"dasd"<<data<<endl;
evbuffer_copyout(input, data, len);
// evbuf.copy_data(input, data, len);
char converted[len];
int i;
for (i = 0; i < len; i++) {
sprintf(&converted[i * 2], "%02X", data[i]);
// cout<<"data is"<< data[i]<<endl;
*/
}
// std::stringstream stream;
// char packet[len];
//cout << "the hex data is" << converted << "with size" << len << endl;
// for(i=0;i<(2*len;i=i+2) {
// string connect_char;
// connect_char.insert(0,"0x");
/// connect_char.append(converted,i,2);
//char *buffer=static_cast<char*>(connect_char);
/// unsigned int buffer=strtoul(connect_char.c_str(), NULL, 16);
// char W = static_cast<char>(buffer);
// cout<<"the characterr is "<<W<<endl;
// }
//char *packet=convert(converted,20);
//cout<<"the packet converted is "<<packet<<endl;
string connect_comd;
//connect_comd="0x";
connect_comd.insert(0, "0x");
connect_comd.append(converted, 0, 2);
// strcpy(connect_comd,converted[0]);
// strcpy(connect_comd,converted[1]);
//unsigned int buf = strtoul(connect_comd.c_str(), NULL, 16);
//int buf=0x10;
int message_type = (ToBits(data[0]).to_ulong());
// cout<<"the message type received now is"<<GET_MESSAGE(data[0])<<endl;
//cout << "the connectcommand is" << buf << endl;
cout << "the message flag received now is" << ToBits(data[0]) << endl;
if (GET_MESSAGE(message_type) == CONNECT) {
cout << "connect packet received from mqtt client" << endl;
ConnectPack_Parser(data, len, accept_fd);
} else if (GET_MESSAGE(message_type) == SUBSCRIBE) {
cout << "subscribe packet received from mqtt client" << endl;
SubscribePack_Parser(data, len, accept_fd);
}
// }
// hexify()
//evbuffer_add_buffer(output, input);
evbuffer_add_buffer(output, input);
//evbuffer_remove_buffer(input,output,len);
free(data);
}
编辑: 我不只是发布修复代码的代码,但我不知道如何避免使用lib事件从服务器端发送。 行'evbuffer_add_buffer(输出,输入);'自动发送我可以从wireshark跟踪的收到的数据包。事情是根据libevent文档的这一行是最佳性能所需。
答案 0 :(得分:0)
the code is working for now.I am posting it for those who may need it. If you only want the read operation don't use the ' evbuffer_add_buffer(output, input)' code since this instantly writes it to the socket or in other words sends the data to the connected client so the CONNECT packet was send simultaneously