[Tutor] Question about socket connections

Joel Ricker joel@prettyhipprogramming.com
17 Sep 2002 17:04:20 -0400


On Tue, 2002-09-17 at 02:12, Rob Brown-Bayliss wrote:

> Another problem I think we both might face is thread safety, more than
> one thread accessing a function.  What thoughts have you there?  

My thinking is that each of my server threads will have access to an
"Inbox" and an "Outbox" of their own that connects to an overall
MessageHandler. Each thread will wait for messages to be received by the
client and stick anything it gets into its Inbox.  The MessageHandler is
watching the Inboxes of all the current threads and then processes them
in turn and at some point puts a new outgoing message into the right
Outbox.  Then the thread will pick up on that and pass it back out.

It looks pretty safe to me but then again, this is all pretty
theoretical at the moment and would love to hear any ideas.

If it helps you any, this is what I have so far for my server.  

import SocketServer
import threading

class MessageObject:

    def pack(self, str):
        return "Blah"

    def unpack(self, str):
        return "Blah"

class MyHandler(SocketServer.BaseRequestHandler):

    def setup(self):
        self.peer = self.request.getpeername()
        print "New Connection From %s:%d" % self.peer
        
    def handle(self):                
        while 1:
            dataReceived, (addr, port) = self.request.recvfrom(1024)
            if not dataReceived: break            
            print MessageObject().unpack(dataReceived)
            self.request.send(MessageObject().pack("OK"))

    def finish(self):
        print "Connection closed."

myServer = SocketServer.ThreadingTCPServer(('', 8881), MyHandler)
myServer.serve_forever()

HTH
Joel