简体   繁体   English

使用Node.js接收特定的TCP命令并进行处理

[英]Receiving specific TCP commands with nodejs and handling them

I have a device in my local that sends JSON data through TCP: 我的本地设备有一台通过TCP发送JSON数据的设备:

ex. {"cmd": "listactions", "id": 13, "value": 100}

The data is send from 192.168.0.233 on port 8000 (I've checked this with wireshark) 数据从端口8000上的192.168.0.233发送(我已经用wireshark检查过)

I would like to (with my homeserver) intercept those specific commands with nodejs & send them through with pusher . 我想(和我的家庭服务器一起)使用nodejs截获这些特定命令,并通过pusher发送它们。

I have very little experience with nodejs & can't seem to get this working. 我对nodejs的经验很少,似乎无法正常工作。 I tried the following: 我尝试了以下方法:

net = require('net');

var server = net.createServer(function(sock) {
    sock.setEncoding('utf8');

    sock.on('data', function (data) {
        // post data to a server so it can be saved and stuff
        console.log(data);

        // close connection
        sock.end();
    });

    sock.on('error', function (error) {
        console.log('******* ERROR ' + error + ' *******');

        // close connection
        sock.end();
    });

});

server.on('error', function (e) {
    console.log(e);
});

server.listen(8000, '192.168.0.233', function(){
    //success, listening
    console.log('Server listening');
});

But it complaints about EADDRNOTAVAIL , from research I've learned that this means the port is in use... Which I don't understand because I'm able to with Wireshark. 但是它抱怨EADDRNOTAVAIL ,从研究中我得知这意味着该端口正在使用中。。。我不明白,因为我能够使用Wireshark。

What's the correct way to do this? 正确的方法是什么?

Wireshark doesn't listen on all ports. Wireshark不会在所有端口上监听。 It uses a kernel driver (with libpcap or winpcap) to "sniff" data off the wire. 它使用内核驱动程序(带有libpcap或winpcap)来“嗅探”离线数据。 That is, it doesn't sit in between anything. 也就是说,它不位于任何东西之间。 It's not a man-in-the-middle. 这不是一个中间人。 It just receives a copy of data as it is sent along. 它只是在发送时接收数据的副本。

Your application needs to listen on that port if you expect it to receive data. 如果您希望应用程序接收数据,则需要在该端口上侦听。 You should use netstat to figure out what process is listening on port 8000 and kill it. 您应该使用netstat找出正在侦听端口8000的进程并将其杀死。 Then, you can listen on port 8000. 然后,您可以在端口8000上侦听。

You could in theory use libpcap to get your data but that's crazy. 从理论上讲,您可以使用libpcap来获取数据,但这太疯狂了。 There is a ton of overhead, something has to listen on that port anyway (it's a TCP connection after all), and it's extremely complex to filter out what you want. 有大量的开销,无论如何都必须在该端口上侦听某些内容(毕竟这是一个TCP连接),并且筛选出想要的内容非常复杂。 Basically, you would be reimplementing the network stack. 基本上,您将重新实现网络堆栈。 Don't. 别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM