我确信有一个非常简单的解决方案 - 我只是不知道在哪里寻找它。
我有一种方法如下:
@staticmethod
def serverstart(self):
'''
This binds the serverobject to a port (here: 50001) and creates a list of clients.
For each client, a new clientthread object is created. There exist two different lists, one for the
sockets (literally) and one for the clientthreads
'''
logging.getLogger(__name__).info("Servergestartet(Verbindung usw)")
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server.bind(("", 50001))
self.server.listen(1)
#the list for the sockets
self.clients = []
#the list for the clientthreads
self.clientthreads = []
#hallo = "hallo"
self.clientnumber = 0
try:
while True:
lesen, schreiben, oob = select.select([self.server] + self.clients,
[], [])
for sock in lesen:
if sock is self.server:
client, addr = self.server.accept()
myclient = clientthread.Clientthread(client, self.clientnumber, self)
self.clientnumber= self.clientnumber+1
myclient.start()
self.clients.append(client)
self.clientthreads.append(myclient)
print "+++ Client %s verbunden" % addr[0]
#else:
#nachricht = sock.recv(1024)
#ip = sock.getpeername()[0]
#if nachricht:
#print "[%s,%d] %s" % (ip, self.clients.index(sock),nachricht)
#else:
#print "+++ Verbindung zu %s beendet" % ip
#sock.close()
#self.clients.remove(sock)
finally:
logging.getLogger(__name__).info("serverstart ist durchgelaufen")
因此,每当有新客户端连接时,就会创建一个新的 Clientthread 实例。
Clientthread 现在继承自 Threading:
class Clientthread(threading.Thread):
def __init__(self,clientsocket, clientnumber, server):
threading.Thread.__init__(self)
def run(self):
from modules.logic import game
'''
as clientthread inherits from threading.Thread, this is this Thread's run-method.
All it does is start the thread with the processkeysmethod - by now.
'''
logging.getLogger(__name__).info("Runmethode des Clientsockets läuft")
logging.getLogger(__name__).info("Daten aus dem Client werden verarbeitet")
while True:
try:
Clientthread.prepareDataforClient(self)
Clientthread.processkeys(self)
except Exception as e:
print e
现在,当然每个 Clientthread 实例都在同一个全局数据上工作。
我的问题是现在,我该如何同步呢?事实上,其中一个客户端线程无法知道还有多少其他客户端线程 - 从技术上讲,它可以是从零开始的任何数字。
有没有简单的方法来解决这个问题