[Tutor] seeking help to a problem w/ sockets
James Duffy
devsfan1830 at gmail.com
Sun Apr 27 02:56:31 CEST 2008
I have a problem w/ a file transfer receiver. They way it works is it binds
a port for incoming transfer , when the file transfer is complete. It closes
the connection and the socket, then loops back and restarts the bind and
listen. I have it set so that the socket is reuseable, which is why this
works. However, if the program that is using this function is closed while
listening, it appears that it does not "un-bind" because when the program is
reopened and a listen attepted to start I get a "port already in use" error.
Only a reboot fixes this issue. This code is imported into a main GUI
script. We have it set to execute some cleanup functions on exit, I need a
function that can dig down to the thread the listener is running in, stop
the listen and close the connection and socket. I basically need to get to
the close function and then stop the while loop. Thanks in advance for any
help anyone can give. My code for the listener class follows:
class Reciever ( Thread ): # the reciever class for the test tool, runs as
a separate thread from the main program
def __init__( this ):
Thread.__init__( this )
def run(this):
this.process()
def bindsock( this ): # create a new socket, bid the socket to the
port, listen until connection recieved
this.Lport=listen
this.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
this.sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
this.sock.bind(('',this.Lport))
this.sock.listen(1)
print "Listening on port " +str(this.Lport)
def acceptsock( this ): #when connection is incoming, accept the
connection
this.conn, this.addr = this.sock.accept()
print 'Got connection from', this.addr
def transfer( this ): #when connection is full established, begin data
download
global filenumber
print 'Starting media transfer '
openfile="XMLrecieved"+str(filenumber)+".xml"
f = open(openfile,"wb") #create and open a new file for writing
incoming data to
while 1:
data = this.conn.recv(1024) #check for incoming data
if not data: break #if not present, break the loop
f.write(data) #if data is present, write it to file and
loop back
f.close() #when loop is broken, close the file
print "Got XML file:" + openfile
print 'Closing media transfer'
filenumber = filenumber + 1
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()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080426/a631a652/attachment.htm>
More information about the Tutor
mailing list