第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

Python Client-Server 如何處理超時(shí)

Python Client-Server 如何處理超時(shí)

Helenr 2022-08-11 17:08:21
我有一個(gè)TCP客戶端 - 服務(wù)器,其中客戶端向服務(wù)器發(fā)送shell命令,服務(wù)器使用所述命令的輸出進(jìn)行響應(yīng)。某些命令(如 date 或 cd)不起作用,因?yàn)樗鼈兪墙换ナ降?,我假設(shè)我的代碼不處理它。每當(dāng)我發(fā)送上述命令時(shí),我的客戶端似乎都掛起了,只是說發(fā)送...我的服務(wù)器從未收到任何東西。我想弄清楚如何處理這種情況,如果發(fā)送命令需要超過5秒的時(shí)間,客戶端將導(dǎo)致超時(shí),或者只是處理它并打印一條消息,指出命令未成功執(zhí)行,同時(shí)保持客戶端連接到服務(wù)器。這是我的代碼客戶:import socket# Clientsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # creates TCP Socket# local host and portLOCAL_HOST = '127.0.0.1'PORT = 5313BUFFER_SIZE = 5000  # size of messagesock.settimeout(5)# connect socket to ip and portsock.connect((LOCAL_HOST, PORT))print("Connected to server\n")print("Enter quit to close connection\n")while True:    message = input("Please enter a command:\n")  # ask user to input message    if message == 'quit':        break    if len(message) == 0:        print("Please enter something")        message = input("Please enter a command:\n")    print("Sending %s" % message)    sock.send(str.encode(message))  # send message    command = str(sock.recv(BUFFER_SIZE), "utf-8")  # receive message    print("received %s" % command)print("closing connection with server")sock.close()服務(wù)器:import socketimport subprocess# Server# Some commands do not work such as cd. Date does not work on windows because it is interactive.# creates TCP socketsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.settimeout(5)# port and server ip(localhost)LOCAL_HOST = ''PORT = 5313BUFFER_SIZE = 5000  # size of message# test connectionprint("Server starting up on %s with port number %s" % (LOCAL_HOST, PORT))# bind socket to ip and portsock.bind((LOCAL_HOST, PORT))# listen to socketsock.listen(1)
查看完整描述

1 回答

?
繁星coding

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超4個(gè)贊

有多種方法可以做到這一點(diǎn),但可能最簡單的方法是調(diào)用subprocess.check_output()方法,該方法允許您以秒為單位指定超時(shí)值,并且還返回子進(jìn)程生成的文本,即:


[...]


while True:

    command = connection.recv(BUFFER_SIZE)  # receive message from client

    if not command:

        break

    command = command.decode("utf-8").strip()

    if len(command) > 0:

        try:

           output_as_string = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True, timeout=5.0).decode("utf-8")

        except subprocess.TimeoutExpired:

           output_as_string = "Sub-process timed out!\r\n"


        connection.send(str.encode("0:") + str.encode(output_as_string))


[...]


查看完整回答
反對(duì) 回復(fù) 2022-08-11
  • 1 回答
  • 0 關(guān)注
  • 216 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)