import socket
# 创建一个socket对象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置接收超时时间为5秒
sock.settimeout(5)
try:
# 连接到服务器(假设服务器在localhost的12345端口上运行)
sock.connect(('localhost', 12345))
# 尝试接收数据
data = sock.recv(1024)
print(f"Received data: {data.decode()}")
except socket.timeout:
print("Connection timed out")
except Exception as e:
print(f"An error occurred: {e}")
finally:
# 关闭socket连接
sock.close()