python - Multi threaded application is not outputting properly -


i have been introduced threading module in python decided play around opened python socket server on port 7000:

import socket s = socket.socket(socket.af_inet,socket.sock_stream) s.bind(('127.0.0.1',7000)) s.listen(1) c, = s.accept() 

and made client server try connecting every port 1 65535 until establishes connection on port 7000. take long multi-threaded it:

import threading import socket import sys host = none def conn(port):     try:         s.connect((host,port))         print 'connected'         sys.exit(1)     except:         pass     global host host = '127.0.0.1' in range(65535):     t = threading.thread(target=conn, args=(i,))     t.start() 

when client connects suppose return message 'connected' when debugging noticed strange behavior program. program return connected, other times program fail output connected server instead terminate without printing anything.

its problem threads. when make client connect port 7000 works 100% of time. threading through 65535 ports causes client not print anything. reason , how can prevent or circumvent it.

edit: realized making try connect smaller number of ports, ports 1-10 , port 7000, gives higher chance of printing out connected.

if connect() fails, consider state of socket unspecified. portable applications should close socket , create new 1 reconnecting.

>>> import socket >>> s = socket.socket(socket.af_inet, socket.sock_stream) >>> s.connect(('127.0.0.1', 6999)) traceback (most recent call last):   file "<stdin>", line 1, in <module>   file "/usr/local/cellar/python/2.7.13/frameworks/python.framework/versions/2.7/lib/python2.7/socket.py", line 228, in meth     return getattr(self._sock,name)(*args) socket.error: [errno 61] connection refused >>> >>> s.connect(('127.0.0.1', 7000)) traceback (most recent call last):   file "<stdin>", line 1, in <module>   file "/usr/local/cellar/python/2.7.13/frameworks/python.framework/versions/2.7/lib/python2.7/socket.py", line 228, in meth     return getattr(self._sock,name)(*args) socket.error: [errno 22] invalid argument >>>  >>> s = socket.socket(socket.af_inet, socket.sock_stream) >>> s.connect(('127.0.0.1', 7000)) # connect success. 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -