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:
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:
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)The "hello!" string never shows up! and the globalVar isn't printed at all. What am I gettin wrong?This is the code:
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)
