def client(address, cause_error=False): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(address) aphorisms = list(zen_utils.aphorisms) if cause_error: sock.sendall(aphorisms[0][:-1]) return for aphorism in random.sample(aphorisms, 3): sock.sendall(aphorism) print(aphorism, zen_utils.recv_until(sock, b'.')) sock.close()
def client(address, cause_error=False): """用于提问的客户端;cause_error为True时,故意不发送【?】定界符,来检测服务器端的异常处理能力""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(address) aphorisms = list(zen_utils.aphorisms) if cause_error: sock.sendall(aphorisms[0][:-1]) #故意发送一个不含【?】定界符的问题 return #不做任何操作,直接返回 for aphorism in random.sample( aphorisms, 3): #在一个【连接套接字】上,与服务器端进行3次对话:sendall()+recvall() sock.sendall(aphorism) #发送问题 print(aphorism, zen_utils.recv_until(sock, b'.')) #在一行中打印发送的问题,和收到的答案 sock.close()
def client(address, cafile): hostname, port = address #ssl.Purpose.SERVER_AUTH参数表示该上下文对象为客户端所用 context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=cafile) raw_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) raw_sock.connect((hostname, port)) print('连接服务器:{}端口:{}'.format(hostname, port)) ssl_sock = context.wrap_socket(raw_sock, server_hostname=hostname) #提出字典的键去访问服务器 aphorisms = list(zen_utils.aphorisms) for aphorism in random.sample(aphorisms, 3): ssl_sock.sendall(aphorism) print(aphorism, zen_utils.recv_until(ssl_sock, b'.')) ssl_sock.close()