【发布时间】:2019-07-17 16:07:30
【问题描述】:
我的 Windows 10 笔记本电脑中有一个 UDP 消息发送套接字,我正在尝试发送一个 JSON 以在 ROS 上解码。 我从命令行写下了一个基本的用户输入函数,如果我输入 1 它将发送带有 hello 的 JSON,如果我输入 2 它将发送带有 hi 的 jasonn。 问题是当我输入 1 时它会发送 bot hi 和 hello 消息包。 我不知道原因,是switch语句的逻辑错误还是winsock2的sendto()函数有问题。
userDialog::UserEntry getUserEntrySendMessage(SOCKET myUdpSocket, sockaddr_in rosBridgeUdpAddress, int addrLen, int BufLen)
{
std::cout<<"please enter what do you like to do:\n";
std::cout << "enter 0 to connect ROSpberry Pi \n";
std::cout << "enter 1 to send HI to ROSpberry Pi\n";
std::cout << "enter 2 to send HELLO to ROSpberry Pi\n";
std::cout << "enter 3 to finish \n";
std::cout << "enter one of those in all UPPERCASE, "
<< "this code does not have an error check yet!\n";
userDialog::UserEntry userInput{};
int x;
std::cin >> x;
userInput = static_cast<userDialog::UserEntry>(x);
switch (userInput)
{
case userDialog::CONNECT_ROS:
{
//creating the JSON message to be sent for initiating the topic
const char* SendBufSTART = { "{ \"op\": \"advertise\", \"topic\": \"myTopic\", \"type\": \"std_msgs/String\" \}" };
std::cout << "I will send this : \n" << SendBufSTART << "\n"; //quick check if JSON is correctly constructed
sendto(
myUdpSocket,
SendBufSTART, //this will be our json
BufLen,// this will be json buffers length
0, //no flags
(SOCKADDR*)& rosBridgeUdpAddress,
//sizeof(rosBridgeUdpAddress) );
addrLen);
return userDialog::CONNECT_ROS;
}
break;
case userDialog::SAY_HI:
{
//creating the JSON message to be sent to be published inside the topic
const char* SendBufHI = { "{ \"op\": \"publish\", \"id\": \"metin's laptop\", \"topic\": \"myTopic\", \"msg\": \{\"data\": \"HI from metin!\"\} \}" };
std::cout << "I will send this : \n" << SendBufHI << "\n"; //quick check if JSON is correctly constructed
sendto(
myUdpSocket,
SendBufHI, //this will be our json
BufLen,// this will be json buffers length
0, //no flags
(SOCKADDR*)& rosBridgeUdpAddress,
//sizeof(rosBridgeUdpAddress) );
addrLen);
return userDialog::SAY_HI;
}
break;
case userDialog::SAY_HELLO:
{
//creating the JSON message to be sent to be published inside the topic
const char* SendBufHELLO = { "{ \"op\": \"publish\", \"id\": \"metin's laptop\", \"topic\": \"myTopic\", \"msg\": \{\"data\": \"HELLO from metin!\"\} \}" };
std::cout << "I will send this : \n" << SendBufHELLO << "\n"; //quick check if JSON is correctly constructed
sendto(
myUdpSocket,
SendBufHELLO, //this will be our json
BufLen,// this will be json buffers length
0, //no flags
(SOCKADDR*)& rosBridgeUdpAddress,
//sizeof(rosBridgeUdpAddress) );
addrLen);
return userDialog::SAY_HELLO;
}
break;
default:
return userDialog::DIALOG_FINAL;
}
return userDialog::DIALOG_FINAL;
}
【问题讨论】:
-
什么消耗getUserEntrySendMessage的结果?这可能是使用您的返回值来发送不同的消息吗?
-
我想支持上面关于
BufLen的评论。它是否足够大以至于它同时发送 SendBufHI 和 SendBufHELLO(它们可能在内存中彼此相邻存储)。