# 這個是客戶端,下邊我會寫幾個關于服務的單執行緒、多執行緒、異步服務端的腳本,
# 定義一個客戶端,
# 匯入接收終端引數、亂數、socket、自己撰寫工具的模塊,
import argparse, random, socket, zen_utils
# 定義客戶端函式,入參為IP地址埠,
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()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Example client')
parser.add_argument('host', help='IP or hostname')
parser.add_argument('-e', action='store_true', help='cause an error')
parser.add_argument('-p', metavar='port', type=int, default=1060,
help='TCP port (default 1060)')
args = parser.parse_args()
address = (args.host, args.p)
client(address, args.e)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/228694.html
標籤:Python
上一篇:Java通過IO流輸出檔案目錄
