Newbie: Keep TCP socket open

Irmen de Jong irmen.NOSPAM at xs4all.nl
Mon May 19 14:29:53 EDT 2008


Alan Wright wrote:

> while (num1<=10) :
> 
>  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>  s.settimeout(10.0)
>  s.connect(("10.1.1.69", 50008)) # SMTP
>  print s.recv(1024) + '\n',
>  num1=num1+1
>  #s.close()
> 
> 
> sys.exit(1) 

I think the following is happening:
Reusing the 's' object for every new socket will make Python to garbage
collect the previous ones. Garbage collecting a socket will likely close() it.
Also after creating all sockets your program exits. I guess either Python or the 
operating system itself will go close all the sockets.


Try putting every new socket you make into a big list instead, so that Python can't 
garbage collect it. And put your program to sleep at the end.

import time
allsockets=[]

while (...):
	s=socket.socket(...
	allsockets.append(s)
	s.settimeout(...
	...

time.sleep(99999)



--irmen



More information about the Python-list mailing list