1

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.

1 Answer 1

3

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();
});
Sign up to request clarification or add additional context in comments.

2 Comments

So this didn't fully answer the question, but it did give me the means to work my way around it, so thank you for that. I have ended up with the following. var client = new net.Socket(); client.connect(PORT, IP_ADDRESS, function() { client.write('Command1'); client.write('Command2'); } However what i now need is to acknowledge the ACK message the client is returning before 'Command2' is being sent. I think this would be done in the callback part of socket.write(data[, encoding][, callback]) however i am completely lost on how to achieve this...
I'm not 100% sure, but maybe something like this? codesandbox.io/s/recursing-cray-6kvdi (this won't run in codesandbox, but you can copy the files and execute it on your machine). Basically what I'm doing is wrapping both the server and the client in a class and restrict sending/receiving messages in the client until the server has sent ACK. Check it out :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.