Sockets and threading

Piet van Oostrum piet at cs.uu.nl
Sun Jul 12 17:52:50 EDT 2009


>>>>> zayatzz <alan.kesselmann at gmail.com> (z) wrote:

>z> Im trying to get aquinted to python on bit more basic level and am
>z> following socket and threading programming tutorials from these 2
>z> addresses :

>z> http://heather.cs.ucdavis.edu/~matloff/Python/PyNet.pdf
>z> http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf

>z> in this PyThreads file he sets up threaded server app which listens to
>z> what clients send to it and echos it back to clients while adding sent
>z> info into one string.

>z> The problem is that the code does not work for me.

>z> class srvr(threading.Thread):
>z> 	v = ""
>z> 	vlock = threading.Lock()
>z> 	id = 0
>z> 	def __init__(self,clntsock):
>z> 		threading.Thread.__init__(self)
>z> 		self.myid = srvr.id
>z> 		srvr.id += 1
>z> 		self.myclntsock = clntsock
>z> 	def run(self):
>z> 		while 1:
>z> 			k = self.myclntsock.recv(1)
>z> 			if k == "": break
>z> 			srvr.vlock.acquire()
>z> 			srvr.v += k
>z> 			srvr.vlock.release()
>z> 			self.myclntsock.send(srvr.v)
>z> 			self.myclntsock.close()


The last line is wrongly indented. It should be outside the loop. Shift
it left so that it lines up with the while. 

What happens now is that the socket is closed after the first recv().
Then the next round in the loop fails because the myclntsock is closed.

-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list