在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)