简体   繁体   English

在python套接字服务器中接受多个客户端

[英]Accepting multiple clients in python socket server

I'm trying to build a simple socket server in python: 我正在尝试在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 我试图通过从外壳程序的多个选项卡调用telnet localhost 5000来测试其功能,但是我得到的模式是

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. 我在彼此之间的4秒钟内调用telnet命令,因此它应该连续连接2条消息,但是仅在断开先前的套接字后才返回该消息。 Why is that and how could I go round fixing this? 为什么会这样,我该如何解决呢?

Its a classic mistake. 这是一个经典的错误。 You called handle() (which slept for 4 seconds) and then tried to create a thread from its result. 您调用了handle() (睡眠了4秒钟),然后尝试根据其结果创建线程。 The target should be a function reference and args should be passed separately. 目标应该是函数引用,而args应该分别传递。

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 . 在此版本中,主线程等待accept ,然后创建运行handle的线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM