连接到设备"/>
[使用nodejs通过UDP连接到设备
我有一个TCP / IP设备,我已经用python编写了脚本来连接数据并从中接收数据,这是可行的。我现在正在尝试使用nodejs做类似的事情,但是根据我尝试过的nodejs方法,不断遇到连接错误或缓冲区安全问题。
这是有效的python脚本;
import socket
import csv
import datetime
from decimal import Decimal
import time
UDP_IP = "10.0.0.122"
UDP_PORT = 1025
MESSAGE = "#01\r"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode(encoding='utf-8'), (UDP_IP, UDP_PORT))
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print ("received message:", str(data))
以下是我尝试的3种方法,它们针对js注释中列出的各种错误。我是Node js的新手,确实可以提供一些帮助。
提前感谢
// //Method 1
// var net = require('net');
// var client = new net.Socket();
// client.connect(1025, '10.0.0.122', function() {
// console.log('Connected');
// client.write('Hello, server! Love, Client.');
// });
// client.on('data', function(data) {
// console.log('Received: ' + data);
// client.destroy(); // kill client after server's response
// });
// client.on('close', function() {
// console.log('Connection closed');
// });
//Method 2
// // Include Nodejs' net module.
// const Net = require('net');
// // The port number and hostname of the server.
// const port = 1025;
// const host = '10.0.0.122';
// // Create a new TCP client.
// const client = new Net.Socket();
// // Send a connection request to the server.
// client.connect({ port: port, host: host }), function() {
// // If there is no error, the server has accepted the request and created a new
// // socket dedicated to us.
// console.log('TCP connection established with the server.');
// // The client can now send data to the server by writing to its socket.
// client.write('#01\r');
// };
// // The client can also receive data from the server by reading from its socket.
// client.on('data', function(chunk) {
// console.log(`Data received from the server: ${chunk.toString()}.`);
// // Request an end to the connection after the data has been received.
// client.end();
// });
// client.on('end', function() {
// console.log('Requested an end to the TCP connection');
// });
//Method 1 and 2 give this error
// events.js:287
// throw er; // Unhandled 'error' event
// ^
// Error: connect ECONNREFUSED 10.0.0.122:1025
/ / at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
// Emitted 'error' event on Socket instance at:
// at emitErrorNT (internal/streams/destroy.js:92:8)
// at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
// at processTicksAndRejections (internal/process/task_queues.js:84:21) {
// errno: 'ECONNREFUSED',
// code: 'ECONNREFUSED',
// syscall: 'connect',
// address: '10.0.0.122',
// port: 1025
// }
//Method 3
var PORT = 1025;
var HOST = '10.0.0.122';
var dgram = require('dgram');
var message = new Buffer('#01\r');
var client = dgram.createSocket('udp4');
client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {
if (err) throw err;
console.log('UDP message sent to ' + HOST +':'+ PORT);
client.close();
});
//Method 3 error
// [Running] node "c:\Users\admin\Nodejs tcp test\app.js"
// (node:6032) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability
issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
// UDP message sent to 10.0.0.122:1025
// [Done] exited with code=0 in 0.155 seconds
回答如下:我已经在Google的帮助下找到了它。 js中有一些很好的UDP连接示例。
[使用Rodrigoms github项目中的正确方向的指针,https://github/rodrigoms2004/ServerSocketTCP_UDP
我使用以下代码设法达到与获取python文件相同的效果。
const udp = require('dgram')
// creating a client socket
const client = udp.createSocket('udp4')
//buffer msg
const data = Buffer.from('#01\r')
client.on('message', (msg, info) => {
console.log('Data received from server : ' + msg.toString())
console.log('Received %d bytes from %s:%d\n', msg.length, info.address, info.port)
})
//sending msg
client.send(data, 1025, '10.0.0.122', error => {
if (error) {
console.log(error)
client.close()
} else {
console.log('Data sent !!!')
}
})
setTimeout( () => {
client.close()
},1000)
更多推荐
[使用nodejs通过UDP连接到设备
发布评论