Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Python socket server that listens on a file descriptor?

I am trying to make a Javascript (Nodejs) app communicate with a Python app.

I got something working using a socket bound to my localhost and a specific port.

To make things simpler (e.g., when deploying to environments that may not allow me to listen on multiple ports), I wanted to change my implementation to use a socket bound to a file descriptor.

I searched high and low, but all examples I found use ports.

Basically I need the Python server counter part to this example from the Nodejs docs (the version specifying a path):

var client = net.connect({path: '/tmp/echo.sock'}.

Could someone please provide a simple example showing, creation and binding a file descriptor socket and processing data on it and/or point me in the right direction?

like image 645
Thorsten Lorenz Avatar asked Jul 22 '12 02:07

Thorsten Lorenz


1 Answers

I modified the this nice example a bit (e.g., python server has to listen on TCP instead UDP socket to be compatible with nodejs client.

I'm posting python server and nodejs client code here for reference:

Python Server:

import socket
import os, os.path
import time

sockfile = "./communicate.sock"

if os.path.exists( sockfile ):
  os.remove( sockfile )

print "Opening socket..."

server = socket.socket( socket.AF_UNIX, socket.SOCK_STREAM )
server.bind(sockfile)
server.listen(5)

print "Listening..."
while True:
  conn, addr = server.accept()

  print 'accepted connection'

  while True: 

    data = conn.recv( 1024 )
    if not data:
        break
    else:
        print "-" * 20
        print data
        if "DONE" == data:
            break
print "-" * 20
print "Shutting down..."

server.close()
os.remove( sockfile )

print "Done"

Nodejs Client:

Uses npmlog to get colored log output npm install npmlog

var net = require('net')
  , log = require('npmlog')
  , sockfile = './communicate.sock'
  ;

var client = net.connect( { path: sockfile });

client
  .on('connect', function () {
    log.info('client', 'client connected');
    client.write('hello server');
  })
  .on('data', function (data) {
    log.info('client', 'Data: %s', data.toString());
    client.end(); 
  })
  .on('error', function (err) {
    log.error('client', err);
  })
  .on('end', function () {
    log.info('client', 'client disconnected');
  })
  ;
like image 129
Thorsten Lorenz Avatar answered Sep 28 '22 07:09

Thorsten Lorenz