我所有的客戶插座做同樣的事情:發送每一秒(22個字節)包如下如何保持通過監聽連接的TCP套接字「選擇」
Server代碼:
import select
import socket
import datetime
SList = []
class Tserver:
def __init__(self, portNum):
host = '127.0.0.1'
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server.bind((host, portNum))
self.server.listen(1)
def GETPACK():
# function for CRC check
def CRC(DATA_STR):
return 1
# generate 100 sockets to listen
for x in range(100):
SList.append(Tserver(x+10000))
inputs = []
# put in inputs
for x in range(100):
inputs.append(SList[x].server)
while(True):
ready_socks, _, _ = select.select(inputs, [], [])
for sock in ready_socks:
c, addr = sock.accept()
while(True):
data = c.recv(22)
if len(data) == 22: # To make sure the data-length is 22
# Turn the pack string into bytearray
data_bytes = bytearray()
data_bytes.extend(data)
if CRC(data_bytes) == 1:
print "Connected from client IP Address:" + str(addr)
# ID
ID = 256*data_bytes[1] + data_bytes[2]
print "ID: ", ID
now = datetime.datetime.now()
print "now: ", str(now)
if __name__ == "__main__":
GETPACK()
我的服務器只能打印由第一個連接的套接字發送的包。 而我的問題是如何打印出每個端口發送到服務器的所有消息。
您是否嘗試調試您的代碼? – peterh
套接字只是不這樣工作。您應該重新閱讀我相信的套接字文檔。您只創建一個套接字來偵聽端口,然後'accept'將爲每個連接返回一個新創建的套接字。 – spectras
@peterh不是,我仍在努力。需要一些好的建議。 –