在Python中,網絡編程通常涉及循環打印的操作,這里列舉一些常用的技巧:
while True:
data = client_socket.recv(1024)
if not data:
break
print("Received data:", data.decode())
# 發送數據
client_socket.sendall(b"Hello, Server!")
import threading
def handle_client(client_socket):
while True:
data = client_socket.recv(1024)
if not data:
break
print("Received data:", data.decode())
# 發送數據
client_socket.sendall(b"Hello, Server!")
# 啟動多個線程處理多個客戶端連接
while True:
client_socket, addr = server_socket.accept()
print("Connected to", addr)
t = threading.Thread(target=handle_client, args=(client_socket,))
t.start()
import select
inputs = [server_socket]
outputs = []
while True:
readable, writable, exceptional = select.select(inputs, outputs, inputs)
for s in readable:
if s is server_socket:
client_socket, addr = server_socket.accept()
inputs.append(client_socket)
print("Connected to", addr)
else:
data = s.recv(1024)
if not data:
inputs.remove(s)
else:
print("Received data:", data.decode())
outputs.append(s)
for s in writable:
s.sendall(b"Hello, Server!")
outputs.remove(s)