Last active
September 23, 2024 01:34
-
-
Save low-ghost/e7c1fc472a03ee271bc1a7abe9cc3635 to your computer and use it in GitHub Desktop.
Simple Python to Javascript 2 way unix socket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) | |
); |
nice one
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?
Great
Thanks this helped a lot
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
awesome