2
我的列表包含連接到我的程序的客戶端的IP地址和端口號。管理線程角色是將每個當前連接的客戶端IP地址和端口號以這種字符串格式發送到管理客戶端 - 例如'172.0.0.1 1234'。關於如何發送每個地址以便它只顯示管理客戶端程序中當前連接的地址和端口號,我可以提供一些建議嗎?通過套接字從列表發送字符串以實時顯示
AddressList中是一個全局變量列表
這裏是我的代碼 -
服務器
import threading
import socket
import math
import random
import ssl
addressList = []
def within(guess,goal,n):
absValue = abs(guess - goal)
if absValue <= n:
return True
else:
return False
def HandleAdmin(adminSocket,):
global addressList
(c,a) = adminSocket.accept()
ts = ssl.wrap_socket(c, certfile="5cc515_server.crt",
keyfile="5cc515_server.key",
server_side=True,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs="5cc515-root-ca.cer")
if ts.recv(80).decode() == 'Hello\r\n':
ts.send('Admin-Greetings\r\n'.encode())
if ts.recv(80).decode() == 'Who\r\n':
for addr in addressList:
ts.send(addr).encode()
ts.close()
return
def HandleClient(c,a):
global addressList
address, port = a
address = str(address) + ' ' + str(port)
addressList.append(address)
scoreCount = 0
guess = 0
if(c.recv(80).decode()) == 'Hello\r\n':
c.send('Greetings\r\n'.encode())
goal = random.randrange(1,21)
while guess!= goal:
guess =c.recv(80).decode()
guess = int(guess[7:len(guess)-2])
if guess == goal:
c.send('Correct\r\n'.encode())
elif within(guess, goal, 2) == True:
c.send('Close\r\n'.encode())
else:
c.send('Far\r\n'.encode())
c.close()
return
clientSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientSocket.bind(("127.0.0.1",4000))
clientSocket.listen(5)
adminSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
adminSocket.bind(("127.0.0.1",4001))
adminSocket.listen(5)
handleAdminThread = threading.Thread(target = HandleAdmin,
args = (adminSocket,))
handleAdminThread.start()
while True:
(c,a) = clientSocket.accept()
clientThread = threading.Thread(target = HandleClient, args = (c,a))
clientThread.start()
管理客戶端
import ssl
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ts = ssl.wrap_socket(s, certfile="100298750.crt",
keyfile="100298750.key",
ca_certs="5cc515-root-ca.cer")
ts.connect(('127.0.0.1', 4001))
ts.send("Hello\r\n".encode())
addressList = []
if ts.recv(80).decode() == "Admin-Greetings\r\n":
print("The players currently playing are:\n\n")
ts.send("Who\r\n".encode())
while True:
print(ts.recv(80).decode())
任何建議,也比沒有更好的建議,對嗎? xD 所以我對套接字知之甚少,所以我很抱歉如果我的建議沒用。但是這裏是:如何,當它們斷開連接時,就在程序終止之前,讓它向管理員發送類似「127.0.0.1 1234 quit」的內容。 –
我寧願任何連接都消失在屏幕之外。所以每次有新的連接或連接被刪除時,它都會發送刷新的列表中的內容。我只在2個月前開始學習python,所以我的技能比基本的要少 – Pete
Ehm當時的代碼實際上工作嗎?因爲如果是這樣,我什至不知道如何:P –