Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 10th, 2012  |  syntax: None  |  size: 1.20 KB  |  hits: 7  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How do I create a Python socket server that listens on a file descriptor
  2. import socket
  3. import os, os.path
  4. import time
  5.  
  6. sockfile = "./communicate.sock"
  7.  
  8. if os.path.exists( sockfile ):
  9.   os.remove( sockfile )
  10.  
  11. print "Opening socket..."
  12.  
  13. server = socket.socket( socket.AF_UNIX, socket.SOCK_STREAM )
  14. server.bind(sockfile)
  15. server.listen(5)
  16.  
  17. print "Listening..."
  18. while True:
  19.   conn, addr = server.accept()
  20.  
  21.   print 'accepted connection'
  22.  
  23.   while True:
  24.  
  25.     data = conn.recv( 1024 )
  26.     if not data:
  27.         break
  28.     else:
  29.         print "-" * 20
  30.         print data
  31.         if "DONE" == data:
  32.             break
  33. print "-" * 20
  34. print "Shutting down..."
  35.  
  36. server.close()
  37. os.remove( sockfile )
  38.  
  39. print "Done"
  40.        
  41. var net = require('net')
  42.   , log = require('npmlog')
  43.   , sockfile = './communicate.sock'
  44.   ;
  45.  
  46. var client = net.connect( { path: sockfile });
  47.  
  48. client
  49.   .on('connect', function () {
  50.     log.info('client', 'client connected');
  51.     client.write('hello server');
  52.   })
  53.   .on('data', function (data) {
  54.     log.info('client', 'Data: %s', data.toString());
  55.     client.end();
  56.   })
  57.   .on('error', function (err) {
  58.     log.error('client', err);
  59.   })
  60.   .on('end', function () {
  61.     log.info('client', 'client disconnected');
  62.   })
  63.   ;