[Tutor] from netcat to socket
János Juhász
janos.juhasz at VELUX.com
Wed Aug 8 14:18:07 CEST 2007
Dear All,
I made a small script to emulate a jetdirect device and capture the data
sent
from SAP to three separate barcode printers.
I need it to make backup for the SAP printing, as I can place the captured
files onto a local server and place a small batch file beside them,
that can be used to print the files without SAP.
My first version worked with nc.exe (netcat) like so :
from threading import Thread
import os
import time
printers = (('10.36.24.40', 'front'),
('10.36.24.41', 'gable'),
('10.36.24.42', 'top'))
class CaptureThread(Thread):
def __init__(self, address, type):
Thread.__init__(self)
self.setDaemon(True)
self.address = address
self.type = type
self.port = 9100
def run(self):
command = 'nc -l -s %s -p %d > %s.prn' %(self.address, self.port,
self.type)
print command
os.system(command)
print '%s is printed' % self.type
time.sleep(2) # wait for two seconds
def capture():
print_threads = []
for ip, name in printers:
print_thread = CaptureThread(ip, name)
print_thread.start()
print_threads.append(print_thread)
# now wait for them to finish
for print_thread in print_threads:
print_thread.join()
if __name__ == '__main__':
while 1:
print '-'*30
capture()
#do stuff with the saved files
I tried to change it to be socket based like so:
from threading import Thread
import os
import time
import socket
## Settings
threads = {'front':{'capt':('127.0.0.1', 9100), 'dest':('127.0.0.1',
9100), 'thread':None},
'gable':{'capt':('127.0.0.1', 9101), 'dest':('127.0.0.1',
9101), 'thread':None},
'top': {'capt':('127.0.0.1', 9102), 'dest':('127.0.0.1',
9102), 'thread':None},
}
class PrinterThread(Thread):
def __init__(self, address, port):
Thread.__init__(self)
self.setDaemon(True)
self.address = address
self.port = port
self.content = ''
self.soc = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
self.soc.bind((address, port))
self.soc.listen(1)
def run(self):
try:
conn, addr = self.soc.accept()
while 1:
data = conn.recv(1024)
self.content += data
if not data:
conn.close()
break
except:
print 'exception (connection closed)'
So the question is, how translate
command = 'nc -l -s %s -p %d > %s.prn' %(self.address, self.port,
self.type)
os.system(command)
to be socket based.
I also would ask your opinions about the structure of 'threads'.
Regards,
Janos
More information about the Tutor
mailing list