假设您有一个相当基本的客户端/服务器代码,其中每个客户端创建三个线程并且多个客户端可以同时连接。我希望服务器等待传入连接,一旦它开始获取连接,就运行直到没有更多线程在运行,然后退出。代码类似于下面。(即,而不是服务器“永远服务”,我希望它在所有线程完成后退出)。
编辑:我希望服务器等待传入连接。一旦连接开始,它应该继续接受连接,直到没有线程运行,然后退出。这些联系会有些零星。
import socket
import threading
# Our thread class:
class ClientThread ( threading.Thread ):
# Override Thread's __init__ method to accept the parameters needed:
def __init__ ( self, channel, details ):
self.channel = channel
self.details = details
threading.Thread.__init__ ( self )
def run ( self ):
print 'Received connection:', self.details [ 0 ]
self.channel.send ( 'hello from server' )
for x in xrange ( 10 ):
print self.channel.recv ( 1024 )
self.channel.close()
print 'Closed connection:', self.details [ 0 ]
# Set up the server:
server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
server.bind ( ( '', 2727 ) )
server.listen ( 5 )
# Have the server serve "forever":
while True:
channel, details = server.accept()
ClientThread ( channel, details ).start()