[英]Python socket programming with threads
I am new to socket programming with threads in python. 我是使用python中的线程进行套接字编程的新手。 I have a simple server app:
我有一个简单的服务器应用程序:
#!/usr/bin/python
from socket import *
from threading import Thread
import _thread
host = ''
port = 52000
sock = socket()
sock.bind((host, port))
sock.listen(5)
print "server is waiting for connections.."
def clientthread():
conn, addr = sock.accept()
print addr, "is connected"
conn.send('Hi! I am server\n') #send only takes string
#Receiving from client
data = conn.recv(1024)
print data
for num in range(5):
Thread(target = clientthread).start()
sock.close()
This simple code works perfectly for 5 clients and after that when one logs out and a new one wishes to contact with server, the application simply closes. 这个简单的代码非常适合5个客户端,然后,当一个客户端注销并希望与服务器联系时,该应用程序便会关闭。 But what I want is to have 5 simultaneous connections, and once anyone have logged out, one client space is recreated to accommodate the new one (ie 5th one currently).
但是我想要的是同时拥有5个连接,一旦任何人注销,便会重新创建一个客户端空间来容纳新的客户端空间(即当前的第5个)。 I believe threading module can help me here.
我相信线程模块可以在这里为我提供帮助。 Its functions like
acquire()
and release()
. 它的功能类似于
acquire()
和release()
。 But not sure how? 但不确定如何? Please help.
请帮忙。
You have to join your threads before closing your socket. 关闭套接字之前,必须先加入线程。
Currently, you are simply starting 5 threads and closing server socket right after. 当前,您只需启动5个线程,然后立即关闭服务器套接字即可。
Join will simply wait until clientthread
returns. 加入将只等到
clientthread
返回。
Python threading page Python线程页面
join([timeout])
加入([超时])
Wait until the thread terminates.等待线程终止。 This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.
这将阻塞调用线程,直到被调用join()方法的线程终止(正常或通过未处理的异常终止),或直到发生可选的超时为止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.