我对 Sockets 和 NodeJS 还是有点陌生,我希望能够使用 NodeJS 通过纯文本协议与 RoboMaster 机器人通信,而不是像 https://robomaster-dev.readthedocs.io/en/latest/text_sdk/intro.html。我不确定如何使用 NodeJS 执行此操作,如果我的应用程序套接字是客户端或服务器,我会有点困惑。我希望将文档中的示例代码转换为 NodeJS 友好版本,但不确定如何。我已经研究过像 Socket.io 这样的东西,但我不确定这是否是我需要使用的。
任何帮助,将不胜感激。
编辑:我找到了 https://www.hacksparrow.com/nodejs/tcp-socket-programming-in-node-js.html#writing-a-tcp-client,它看起来与我需要的非常相似,但我不确定。
回答1
事实证明,我可以使用 net 模块与 RoboMaster 机器人进行通信。使用 https://www.hacksparrow.com/nodejs/tcp-socket-programming-in-node-js.html#writing-a-tcp-client 中的代码如下所示:
var net = require('net');
var HOST = '192.168.2.1';
var PORT = 40923;
var client = new net.Socket();
client.connect(PORT, HOST, function () {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('command;');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function (data) {
console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function () {
console.log('Connection closed');
});