[Tutor] python sockets
Jon Engle
jon.engle at gmail.com
Wed Jun 11 14:42:24 CEST 2014
Thank you for your help, this definitely gets me going in the right
direction!
On Wed, Jun 11, 2014 at 4:16 AM, Marc Tompkins <marc.tompkins at gmail.com>
wrote:
> On Tue, Jun 10, 2014 at 4:08 PM, Jon Engle <jon.engle at gmail.com> wrote:
> > Ok, so when I run the code it immediately terminates and never 'listens'
> to
> > the ports in the loop. I have verified by running netstat -an | grep
> 65530
> > and the startingPort is not binding.
>
> The problem is that all threads started by a program terminate when
> the program terminates - and you haven't told your program to stick
> around when it's done setting up. So it's setting up and then
> immediately exiting - and by the time you run netstat a few seconds
> later you find nothing. (Also, by leaving HOST = '', you're listening
> at address 0.0.0.0, so good luck catching any traffic...)
> Try something like this:
>
>
> #!/usr/bin/python # This is server.py file
> from socket import * #import the socket library
> import thread #import the thread library
>
> def setup(PORT):
> HOST = '127.0.0.1' #we are the host
> ADDR = (HOST,PORT) #we need a tuple for the address
> BUFSIZE = 4096 #reasonably sized buffer for data
>
> serv = socket( AF_INET,SOCK_STREAM)
>
> serv.bind((ADDR)) #the double parens are to create a tuple with
> one element
> serv.listen(5) #5 is the maximum number of queued connections we'll
> allow
> print '\nlistening on port %i...' % PORT
> conn,addr = serv.accept() #accept the connection
> print '\n...port %i connected!' % PORT
> conn.send('TEST')
> conn.close()
>
> def main():
> startingPort=int(raw_input("\nPlease enter starting port: "))
> for port in range (startingPort, 65535):
> thread.start_new_thread(setup, (port,))
> quitNow = ''
> while quitNow not in ('Q', 'q'):
> quitNow = raw_input('Enter Q to quit.')
>
> if __name__ == '__main__':
> main()
>
>
> This will stick around until you enter 'Q', and if you run netstat in
> another window you'll see that it's LISTENING on all the ports you
> asked for. (All of those print statements will show up in a
> surprising order!)
>
> I'm not running the other side of this experiment, so I haven't tested
> a successful connection... good luck.
>
--
Cheers,
Jon S. Engle
jon.engle at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140611/b6eec68f/attachment.html>
More information about the Tutor
mailing list