|
Versions Of This Snippet::
Download a raw-text version of this code by clicking on "Download Version"
Latest Snippet Version: :0.9
#!/usr/bin/python
# small server program
# which saves input from socket to a file
# supports only a single session from one tcp client
# can be tested with: telnet <hostname> <portnumber>
# peter.bauer@inode.at
import socket, time
filename="/var/log/call_log.txt"
while 1: # repeat forvever
fileh=open(filename,"a") # open file for appending
HOST = '' # Symbolic name meaning all available interfaces
PORT = 20000 # Arbitrary non-privileged port
try: # listen, only for a single session
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1: # repeat while data from tcp socket
data = conn.recv(1024) # wait for a message to arrive
if not data: break #
conn.send(data) # send echo back to sender
fileh.write(data) # write to file
fileh.flush() # flush data to file
print data, # only for diagnosis
conn.close() # close conn
fileh.close() # close filehandle
# repeat with file open
# catch error:
except socket.error: # can happen on socket open
if s: # if tcp port is still used from
s.close() # previous session
print "Could not open socket: "
time.sleep(10) # continue listening
Submit a new versionYou can submit a new version of this snippet if you have modified it and you feel it is appropriate to share with others..
|
||||||||||||||||||||||||||
