Bula
Bula

Reputation: 2792

Accepting multiple clients in python socket server

I'm trying to build a simple socket server in python:

import socket
import threading
import time


def handle(conn_addr):
  print("Someone Connected")
  time.sleep(4)
  print("And now I die")


host = ''
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
  s.bind((host,port))
except socket.error as e:
  print(str(e))

s.listen(2)

while True:
  threading.Thread(handle(s.accept())).start()


print("Should never be reached")

The socket server should accept multiple clients at the same time. I tried to test its functionality by calling telnet localhost 5000 from multiple tabs from my shell however the pattern that i get is

Someone Connected
And now I die
Someone Connected
And now I die

Instead of

Someone Connected
Someone Connected
Someone Connected

I call the telnet command within 4 seconds of each other so it should have 2 messages of connected in a row however the message is only returned after the previous socket is disconnected. Why is that and how could I go round fixing this?

Upvotes: 3

Views: 9170

Answers (1)

tdelaney
tdelaney

Reputation: 77407

Its a classic mistake. You called handle() (which slept for 4 seconds) and then tried to create a thread from its result. The target should be a function reference and args should be passed separately.

threading.Thread(target=handle, args=(s.accept(),)).start()

In this version, the main thread waits for an accept and then creates the thread that runs handle.

Upvotes: 4

Related Questions