我对 node.js
一无所知。
在我的 previous question 之后关于如何使用 C++
发送 UDP
字符串文本并从 Node.js
接收它,我正在考虑接收数字(更一般地说,接收对象)。
我得到的结果是二进制格式的丑陋字符。我应该如何修复它们?
结果:
127.0.0.1:1414 - (�@
127.0.0.1:1414 - ףp=
(�@
127.0.0.1:1414 - �G�z(�@
127.0.0.1:1414 - ��Q�(�@
127.0.0.1:1414 - \���((�@
127.0.0.1:1414 - 33333(�@
127.0.0.1:1414 -
ףp=(�@
127.0.0.1:1414 - �z�G(�@
127.0.0.1:1414 - ���Q(�@
127.0.0.1:1414 - ���(\(�@
127.0.0.1:1414 - gffff(�@
127.0.0.1:1414 - >
ףp(�@
127.0.0.1:1414 - �G�z(�@
127.0.0.1:1414 - �Q��(�@
127.0.0.1:1414 - ��(\�(�@
127.0.0.1:1414 - �����(�@
127.0.0.1:1414 - q=
ף(�@
127.0.0.1:1414 - H�z�(�@
127.0.0.1:1414 - ��Q�(�@
127.0.0.1:1414 - �(\��(�@
127.0.0.1:1414 - �����(�@
127.0.0.1:1414 - �p=
�(�@
127.0.0.1:1414 - {�G�(�@
127.0.0.1:1414 - R���(�@
127.0.0.1:1414 - )\���(�@
127.0.0.1:1414 - )�@
127.0.0.1:1414 - ףp=
)�@
127.0.0.1:1414 - �G�z)�@
127.0.0.1:1414 - ��Q�)�@
127.0.0.1:1414 - \���()�@
127.0.0.1:1414 - 33333)�@
127.0.0.1:1414 -
应用程序.js
var PORT = 1414;
var HOST = '127.0.0.1';
var dgram = require('dgram');
var server = dgram.createSocket({ type: 'udp4', reuseAddr: true });
server.on('listening', function () {
var address = server.address();
console.log('UDP Server listening on ' + address.address + ":" + address.port);
});
server.on('message', function (message, remote) {
console.log(remote.address + ':' + remote.port +' - ' + message);
});
server.bind(PORT, HOST);
主要.cpp
// g++ main.cpp -o main -std=c++11 -lboost_system -pthread
#include <iostream>
#include <stdio.h>
#include <string>
#include <boost/asio.hpp>
using boost::asio::ip::udp;
int main(int argc, char* argv[])
{
const int port=1414;
const std::string ip="127.0.0.1";
boost::asio::io_service io_service;
udp::resolver resolver(io_service);
udp::endpoint client_endpoint = *resolver.resolve({udp::v4(), ip, std::to_string(port)});
udp::socket socket(io_service, udp::v4());
socket.set_option(boost::asio::socket_base::reuse_address(true));
socket.bind(udp::endpoint(udp::v4(), port));
double data;
for(long i=0;true;i++)
{
data=i*0.01;
socket.send_to(boost::asio::buffer((char *)&data, sizeof(data)), client_endpoint);
usleep(10);
}
return 0;
}
最佳答案
您收到的是Buffer
s,其中包含二进制数据。通过将 message
与字符串连接,您隐式调用了 message.toString()
,默认情况下会将二进制数据转换为 UTF8,这就是您所看到的。
相反,您需要做的是直接从 message
中读取。您可以使用 message.read*()
方法从 Buffer
中读取数字。
但是,您在使用当前代码时仍会遇到一个问题:data
字节的发送顺序取决于主机的 CPU(类型)。最好以网络字节顺序(大端)通过网络发送数据,以确保兼容性和一致性。
假设您运行的是典型的 Intel 或 AMD CPU,您应该能够使用 message.readDoubleLE()
在 node.js 端读取值。
关于javascript - NodeJs 以丑陋的二进制格式接收 UDP 数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39266375/