I'm learning the use of multithreading and sockets in python so I'm sorry if I lack knowledge...
I'm stuck with this problem: I took this code from this forum and I tried to do some modify.
I would like to have the main thread which start a thread which listen for connection and for each connection start a new thread.
In the meanwhile the main thread has to do something (in this case print the globalVar). The globalVar is inscreased by 1 every message received.
The result with this code is:
The "hello!" string never shows up! and the globalVar isn't printed at all. What am I gettin wrong?
This is the code:
I'm stuck with this problem: I took this code from this forum and I tried to do some modify.
I would like to have the main thread which start a thread which listen for connection and for each connection start a new thread.
In the meanwhile the main thread has to do something (in this case print the globalVar). The globalVar is inscreased by 1 every message received.
The result with this code is:
1 2 3 4 5 6 7 8 |
Hi! ( '192.168.2.226' , 5601 ) ( '192.168.2.226' , 5601 ) ( '192.168.2.226' , 5601 ) ( '192.168.2.226' , 5601 ) ( '192.168.2.226' , 5601 ) ( '192.168.2.226' , 5601 ) ( '192.168.2.226' , 5601 ) |
This is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import socket import threading globalVar = 0 class ThreadedServer( object ): global globalVar def __init__( self , host, port): self .host = host self .port = port self .sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self .sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 ) self .sock.bind(( self .host, self .port)) def listen( self ): self .sock.listen( 5 ) while True : client, address = self .sock.accept() client.settimeout( 60 ) threading.Thread(target = self .listenToClient,args = (client,address)).start() def listenToClient( self , client, address): global globalVar size = 1024 while True : try : data = client.recv(size) if data: # Set the response to echo back the recieved data #response = data print (address) globalVar + = 1 #client.send(response) else : raise error( 'Client disconnected' ) except : client.close() return False print ( "Hi!" ) threading.Thread(target = ThreadedServer('', 5050 ).listen()).start() print ( "Hello!" ) while True : print (globalVar) |