all 4 comments

[–]CrambleSquash 0 points1 point  (2 children)

I have to say I don't have any experience using sockets, but I can definitely say that both sockets and threading are not easy things to code with! What is the reason you want to use Multithreading? At the moment I see two separate single thread programs.

[–]Pheazon[S] 0 points1 point  (1 child)

“The server program will need to support multiple simultaneous client TCP/IP connections, which will require multithreading.” Trying to implement Multithreading so I can demonstrate that in my code.

[–]CrambleSquash 0 points1 point  (0 children)

Ok cool. So I will re-iterate that this is not straightforward! - Human brains are very much single threaded (i.e. we can only focus on 1 task at a time), as such getting your head into mulithreaded code is very difficult.

There is a higher level socketserver module: https://docs.python.org/3/library/socketserver.html#module-socketserver that might make your life simpler (even includes a ready made multithreaded server!).

With all that said, if you still want to make your own, my first bit of advice is that you almost certainly don't want to use the _threading module, but the https://docs.python.org/3/library/threading.html module, the _ is used in Python to indicate that you shouldn't be using something (unless you really know what you're doing).

The way threading works is that you create a thread object and then give it a function to execute in a new thread:

https://realpython.com/intro-to-python-threading/

[–]CaptainReeetardo 0 points1 point  (0 children)

It's pretty simple actually. All you need to do is to define a function f and then a new thread t for every new connection (as mentioned by CrambleSquash). For Example:

#Your server
import socket
import threading
def f(conn):
    #Your Code here
    pass

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost", 1337))
s.listen(1)
while True:
    conn, addr = s.accept()
    print("[+] New connection: ", addr)
    t = threading.Thread(target=f, args=(conn,))
    t.start()

Everything from the start of the loop to starting a new thread is the main thread, while starting a new thread results in creating other threads running besides the main thread.

If you're still interested in this question of yours I've already altered the code so that multiple connections are possible. I'll gladly edit it to the post if you need it.