那边的好技术人员
有时我一直在研究这个问题,要求是:我有一个服务器套接字,它将永远运行,它具有3个功能。
1)扫描特定端口号上的所有客户端套接字并将其绑定 2)为每个套接字启动一个线程,并不断读取,直到客户端套接字停止。 3)处理数据并上传到Windows SQL表中。
第一点工作正常,第二个功能问题。代码无法同时从多个客户端读取数据,因此,第一个客户端关闭后,它开始接受第二个客户端的数据。但是我的要求是同时读取2500个客户端的数据。
有人可以帮助我实现同样的目标吗?我在下面粘贴我的代码。
def StreamData(CurrentThread,ThreadName):
print("Listening in " + ThreadName)
while True:
EventData = CurrentThread.recv(EventDataSize).decode('Latin-1')
if len(EventData) > 0:
print(EventData)
testfile.writelines(EventData)
else:
break
CurrentThread.close()
def AddConnectionDetailsToArray(ConnectionDetails):
ConnectionList.append(address)
def JoinStore():
global host
global address
global ConnectionAccepted
global EventDataSize
global MessageStarter
global MessageEnder
global CompleteString
global LetterCounter
global FullRecord
global PartialRecord
global StartRecord
global EndRecord
print("RADAR started, scanning and accepting connections :")
RadarSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
RadarSocket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
RadarSocket.bind((host, PortToBindTo))
RadarSocket.listen(NumberOfSockets)
# Ensure ports are not exhausted
while True:
ready_socks,_,_ = select.select(socks, [], [])
for sock in ready_socks:
data, addr = sock.recvfrom(1024) # This is will not block
print ("received message:", data)
#if ConnectionAccepted < NumberOfSockets:
while True:
try:
connection, address = RadarSocket.accept()
#RadarSocket.setblocking(0) # Prevents time outs
StoreIpList.append(address)
ConnectionList.append(connection)
ConnectionAccepted = ConnectionAccepted + 1
print("Accepted connection from IP: " + str(address[0]) + "\n")
ThreadName = "Newthread " + str(ConnectionAccepted)
Thread(target = AcceptStores.StreamData(connection,ThreadName)).start()
#Now we need to add this connection details to an array to keep
IPAddress = address[0]
AcceptStores.AddConnectionDetailsToArray(IPAddress)
except Exception as e:
RadarErrorString = '{c} - {m}'.format(c = type(e).__name__, m = str(e)) + "\n"
print(RadarErrorString)
else:
print("No more ports to connect")