[Tutor] seeking help to a problem w/ sockets
Mark Tolonen
metolone+gmane at gmail.com
Sun Apr 27 17:13:01 CEST 2008
"James Duffy" <devsfan1830 at gmail.com> wrote in message
news:000001c8a801$89e132d0$9da39870$@com...
[snip]
> def close( this ): #close all connections and sockets
> this.conn.close()
> this.sock.close()
>
> def process( this ): #this is the loop of the thread, it listens,
> receives, closes then repeats until entire program is closed
> while 1:
> this.bindsock()
> this.acceptsock()
> this.transfer()
> this.close()
There is no need to close the server socket after each connection. Try:
def close( this ): #close all connections and sockets
this.conn.close()
def process( this ):
this.bindsock()
while 1:
this.acceptsock()
this.transfer()
this.close()
Also, take a look at the SocketServer libary. It handles multiple
simultaneous connections and the details of setting up and tearing down
connections:
import threading
import SocketServer
class MyHandler(SocketServer.StreamRequestHandler):
def handle(self):
print 'Starting media transfer '
openfile="XMLrecieved"+str(self.server.filenumber)+".xml"
f = open(openfile,"wb")
while 1:
data = self.request.recv(1024)
if not data: break
f.write(data)
f.close()
print "Got XML file:" + openfile
print 'Closing media transfer'
self.server.filenumber += 1
class MyServer(SocketServer.ThreadingTCPServer):
filenumber = 1
class MyThread(threading.Thread):
def run(self):
listen=2222
server = MyServer(('',listen),MyHandler)
server.serve_forever()
t=MyThread()
t.setDaemon(True)
t.start()
--Mark
More information about the Tutor
mailing list