0

I want to send information from my Node.js code to Python using sockets. How can I achieve that?

In pseudo-code, what I want is this:

js:

sendInformation(information)

python:

recieveInformation()
sendNewInformation()

js:

recievNewInformation()
2
  • your pseudo code is very high level. Have you looked at basic socket tutorials and documentation for python and node? Commented Sep 11, 2019 at 23:27
  • I know how to do it in python, I can't figure out the node.js Commented Sep 11, 2019 at 23:28

1 Answer 1

2

You should determine which code is the server and which one is the client. I assume your Python code is your server. You can run a server in python using:

import socket

HOST = '0.0.0.0'
PORT = 9999    

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)

And then you can connect your Nodejs client code to the server:

var net = require('net');

var HOST = '127.0.0.1';
var PORT = 9999;

var client = new net.Socket();
client.connect(PORT, HOST, function() {
  console.log('CONNECTED TO: ' + HOST + ':' + PORT);
  // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
 client.write('Message from client');

});

// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
  console.log('DATA: ' + data);
  // Close the client socket completely
  client.destroy();
});

// Add a 'close' event handler for the client socket
client.on('close', function() {
  console.log('Connection closed');
});

Sign up to request clarification or add additional context in comments.

Comments

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.