rHumphries
rHumphries

Reputation: 11

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.

Upvotes: 1

Views: 1591

Answers (1)

eol
eol

Reputation: 24555

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();
});

Upvotes: 3

Related Questions