简体   繁体   中英

Send simple TCP messages in JavaScript, similarly to Python .socket

Coming from Python, I am trying to achieve a similar result using JavaScript and node.js .

I am trying to send a simple TCP message across a network. In Python , I would achieve this in the following way:

import socket

device_ip = '192.168.0.10'
device_port = 20000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
s.connect((device_ip, device_port))

command = ('Message to be sent to device here')
s.sendall(command.encode())
s.recv(4096)

I have looked at node's socket.io module, but I couldn't find anything as simple as the above solution in Python .

The device at the end of device_ip will respond to the message so long as it is TCP encoded, it will then just send back an Ack message which the JS can effectively ignore. The Ack messages only exist as a simple handshake before sending another message. I have the Python code working as desired, but I find myself needing to run this with JS and Node .

Node provides the Net - module which basically allows you to create tcp-server and client sockets. Here's a very simple example for a server-socket:

const net = require('net');
const server = net.createServer((c) => {
    console.log('client connected');
    c.on('end', () => {
        console.log('client disconnected');
    });
    c.write('hello\r\n');
    c.pipe(c);
});

server.listen(20000, () => {
    console.log('server socket listening ...');
});

And here's the code for a corresponding client-socket:

const net = require('net');
const client = net.createConnection({ port: 20000}, () => {
    client.write('world!\r\n');
});
client.on('data', (data) => {
    console.log(data.toString());
    client.end();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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