[Tutor] python sockets
Peter Otten
__peter__ at web.de
Wed Jun 11 10:44:20 CEST 2014
Jon Engle 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.
As I've already hinted the easiest way to keep your listening threads alive
is to use the threading instead of the thread module:
$ cat bind_ports.py
#!/usr/bin/python
import socket
import threading
import sys
HOST = ''
STARTPORT = int(sys.argv[1])
ENDPORT = int(sys.argv[2])
def setup(port):
print 'setting up port', port
addr = (HOST, port)
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv.bind(addr)
serv.listen(1)
conn, addr = serv.accept()
print 'port', port, '...connected!'
conn.sendall('TEST')
conn.close()
print 'port', port, '...CLOSED!'
if __name__ == "__main__":
for port in range(STARTPORT, ENDPORT):
threading.Thread(target=setup, args=(port,)).start()
$ python bind_ports.py 11110 11113 &
[1] 9214
$ setting up port 11110
setting up port 11111
setting up port 11112
netstat -an | grep 1111
tcp 0 0 0.0.0.0:11110 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:11111 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:11112 0.0.0.0:* LISTEN
To test it I've applied a minor modification to the client of the echoserver
example in https://docs.python.org/2/library/socket.html#example
$ cat read_socket.py
import socket
import sys
HOST = 'localhost'
PORT = int(sys.argv[1])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
$ python read_socket.py 11110
port 11110 ...connected!
port 11110 ...CLOSED!
Received 'TEST'
$ python read_socket.py 11112
port 11112 ...connected!
port 11112 ...CLOSED!
Received 'TEST'
$ python read_socket.py 11111
port 11111 ...connected!
port 11111 ...CLOSED!
Received 'TEST'
$ fg
bash: fg: Programm ist beendet.
[1]+ Fertig python bind_ports.py 11110 11113
$
More information about the Tutor
mailing list