Skip to content

Instantly share code, notes, and snippets.

@low-ghost
Last active September 8, 2021 11:41
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save low-ghost/e7c1fc472a03ee271bc1a7abe9cc3635 to your computer and use it in GitHub Desktop.
Save low-ghost/e7c1fc472a03ee271bc1a7abe9cc3635 to your computer and use it in GitHub Desktop.
Simple Python to Javascript 2 way unix socket
"""Creates a python socket client that will interact with javascript."""
import socket
socket_path = '/tmp/node-python-sock'
# connect to the unix local socket with a stream type
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
client.connect(socket_path)
# send an initial message (as bytes)
client.send(b'python connected')
# start a loop
while True:
# wait for a response and decode it from bytes
msg = client.recv(2048).decode('utf-8')
print(msg)
if msg == 'hi':
client.send(b'hello')
elif msg == 'end':
# exit the loop
break
# close the connection
client.close()
/**
* Creates a unix socket server and waits for a python client to interact
*/
const net = require('net');
const fs = require('fs');
const socketPath = '/tmp/node-python-sock';
// Callback for socket
const handler = (socket) => {
// Listen for data from client
socket.on('data', (bytes) => {
// Decode byte string
const msg = bytes.toString();
console.log(msg);
if (msg === 'python connected')
return socket.write('hi');
// Let python know we want it to close
socket.write('end');
// Exit the process
return process.exit(0);
});
};
// Remove an existing socket
fs.unlink(
socketPath,
// Create the server, give it our callback handler and listen at the path
() => net.createServer(handler).listen(socketPath)
);
@TarchyV
Copy link

TarchyV commented Dec 9, 2020

awesome

@paulgrammer
Copy link

nice one

@gerfnitauthor
Copy link

I need the exact opposite. A Javascript client running on a PC/Mac interacting with a Python server. How difficult to change what you've already written?

@muthu-kumaravel
Copy link

Great
Thanks this helped a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment