Skip to content

Instantly share code, notes, and snippets.

@low-ghost
Last active September 23, 2024 01:34
Show Gist options
  • Select an option

  • Save low-ghost/e7c1fc472a03ee271bc1a7abe9cc3635 to your computer and use it in GitHub Desktop.

Select an option

Save low-ghost/e7c1fc472a03ee271bc1a7abe9cc3635 to your computer and use it in GitHub Desktop.

Revisions

  1. low-ghost revised this gist Jan 8, 2017. No changes.
  2. low-ghost created this gist Dec 18, 2016.
    22 changes: 22 additions & 0 deletions client.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    """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()
    36 changes: 36 additions & 0 deletions server.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    /**
    * 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)
    );