socketServer questions

Tim Williams (gmail) tdwdotnet at gmail.com
Sat Oct 8 09:35:50 EDT 2005


On 07/10/05, rbt <rbt at athop1.ath.vt.edu> wrote:
> I have written a python socketServer program and I have a few questions

This is a multithreaded non-blocking version of your server (not
tested), with a basic attempt to hande errors.

from socket import *
from SocketServer import *
import  time, threading, sys

class tr_server(ThreadingMixIn, TCPServer):
    def some_function(self):
        pass

class tr_handler(StreamRequestHandler):
    global write_to_file, file_path

    def handle(self):
        print "Current Connection count:", threading.activeCount() -1
        public_ip = self.client_address[0]
        serv_date = time.strftime('%Y-%m-%d', time.localtime())
        serv_time = time.strftime('%H:%M:%S', time.localtime())

        try:
            data = self.rfile.readline(300)
            data = str.strip(data)
            bytes = str(len(data))
            # Note that 'data; comes from the client.
            fp = file('/home/rbt/Desktop/tr_report.txt', 'a')
            fp.write(data+"\t"+serv_date+"\t"+serv_time+"\t"+public_ip+"\t"+bytes+"\n")
            fp.close()
        except:
            print "unknown error", sys.exc_info()[0]

def StartServer():
    setdefaulttimeout( 30  )  # timeout incoming connections
    server = tr_server(('', 55503 ), tr_handler)
    server.serve_forever()

if __name__ == '__main__':
    StartServer()

Consider putting the writing to file function in its own class or
thread.  Then opening the file once and appending the data to it from
each connection. Yoou would need to use fp.flush() after each
fp.write()  so that the data survives a program fail.

HTH :)



More information about the Python-list mailing list