1

So I have this code

import socket
def main():
    #does a bunch of argument parsing
while True:
     newsock, fromaddr = s.accept()
     ssl_sock = context.wrap_socket(newsock, server_side=True)
     threading.Thread(target=tls_listener, args=(ssl_sock,)).start()

def tls_listener(ssl_sock):
     #the thing I want to turn into a class
     #calls other functions, does some reporting 



if __name__ == "__main__":
     main()

I want to make the tls_listener a class (it's grown quite a bit, and I've realized I should abstract it (and use self as opposed to passing variables)), but am not sure how to start up instances of a class using threading, as it needs to be passed a function. Should I do something like

class TlsListener(threading):
    #overload run()

or would it be possible to have the thread create new instances of a TlsListener class?

1 Answer 1

1

Assuming you want to create a new instance of the TlsListener class each time you accept a socket, you can simply leave your code as is, and create a new class inside of tls_listener function:

while True:
     newsock, fromaddr = s.accept()
     ssl_sock = context.wrap_socket(newsock, server_side=True)
     threading.Thread(target=tls_listener, args=(ssl_sock,)).start()

def tls_listener(ssl_sock):
    t = TlsListener()  # new instance of TlsListener class
Sign up to request clarification or add additional context in comments.

1 Comment

I can't actually upvote this answer, as I have less than 15 reputation, but thank you! Very simple, elegant solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.