socketServer questions

Tim Williams (gmail) tdwdotnet at
Sat Oct 8 15:35:50 CEST 2005

On 07/10/05, rbt <rbt at> 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):

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())

            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')
            print "unknown error", sys.exc_info()[0]

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

if __name__ == '__main__':

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