出于学习目的,我正在使用Python3中的套接字和线程进行游戏;
我做了一个 server.py (在请求输入es的同时监听多客户端连接。:帮助,退出,监听,停止监听,clients_connected,发送[client] [消息] )。
我尝试以不同的方式同时运行handle_client()和server_command(),但无法与选定的客户端正确通信。
所以,这是实际的代码,没有调用send_commands()。
任何人都可以通过server_commands()帮助我管理所有连接的客户端吗?
谢谢。
import socket
import threading
indirizzo_ip = "192.168.1.239"
porta = 1337
clients = []
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((indirizzo_ip, porta))
server.listen(10)
print(f"In ascolto su: {indirizzo_ip}:{porta}")
def send_commands():
while True:
comando = input("> ")
array = comando.split()
if comando == "sessions":
if not len(clients):
print("Nessun client connesso.")
for client in clients:
print(f"Client connessi:\n{str(len(clients))}: {client}")
else:
print("Comando sconosciuto.")
# Thread di gestione del client
def handle_client(client_socket):
richiesta = client_socket.recv(1024).decode()
clients.append(richiesta)
print(f"\n[*] Connessione da: {richiesta} | {addr[0]}:{addr[1]}")
# send_commands() ?
while True:
global client
client, addr = server.accept()
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()