Python Forum
Multithreading socket in Python. I'm missing something
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Multithreading socket in Python. I'm missing something
#1
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:

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)
Reply
#2
You have two extra parentheses that make your code __main__ invoke ThreadedServer.listen instead of passing a reference to it, and this makes everything run on the same thread. Use instead:
threading.Thread(target=ThreadedServer('',5050).listen).start()
In case of such problems, pepper you code liberally with code such as:
print("{object/method} run on thread:",threading.current_thread().ident)
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Tkinter Simple Multithreading Question AaronCatolico1 5 1,571 Dec-14-2022, 11:35 PM
Last Post: deanhystad
  python Multithreading on single file mg24 3 1,736 Nov-05-2022, 01:33 PM
Last Post: snippsat
  multithreading Hanyx 4 1,325 Jul-29-2022, 07:28 AM
Last Post: Larz60+
Question Problems with variables in multithreading Wombaz 2 1,327 Mar-08-2022, 03:32 PM
Last Post: Wombaz
  Missing Schema-Python Question Andwconteh 1 2,517 Jun-16-2021, 01:00 PM
Last Post: Andwconteh
  Multithreading question amadeok 0 1,781 Oct-17-2020, 12:54 PM
Last Post: amadeok
  How can i add multithreading in this example WoodyWoodpecker1 3 2,514 Aug-11-2020, 05:30 PM
Last Post: deanhystad
  matplotlib multithreading catosp 0 2,951 Jul-03-2020, 09:33 AM
Last Post: catosp
  Missing Python Library Novecento99 8 3,748 Jan-21-2020, 09:05 PM
Last Post: snippsat
  First Byte of a string is missing while receiving data over TCP Socket shahrukh1987 3 4,245 Nov-20-2019, 10:34 AM
Last Post: shahrukh1987

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020