簡體   English   中英

使用 Python 在終端中運行聊天室時出現無限循環錯誤

[英]Infinite Loop Error while Running Chatroom in Terminal using Python

我已經使用 python 實現了一個簡單的聊天室。 當用戶退出(關閉終端窗口)時,程序會中斷並顯示一條消息的無限循環。 我有以下代碼來處理異常(當沒有收到消息時),但是它不會 go 進入,也不會關閉客戶端套接字連接。 關於斷開連接后如何關閉客戶端套接字的任何幫助將不勝感激? 謝謝!

def handle(client):
    while True:
        try:
            message = client.recv(1024)
            messages = message.decode('ascii')
            index = clients.index(client)
            clientname = clientnames[index]
            print("<{}> {}".format(clientname, messages))
            broadcast("({}) {}".format(clientname, messages).encode('ascii'), index)
        except:
            index = clients.index(client)
            clientname = clientnames[index]
            print("{} left!".format(clientname))
            broadcast('{} left!'.format(clientname).encode('ascii'), index)
            clientnames.remove(clientname)
            clients.remove(client)
            client.close()
            break

根據我的評論,給你這段代碼。 如果它立即工作,我不知道,因為我還沒有看到你實現的其他方法。 特別是,檢查messages是否是列表或顧名思義並相應更改。

Function:如果你向機器人發送quit ,一切都會被關閉

def handle(client):
    while True:
        try:
            message = client.recv(1024)
            messages = message.decode('ascii')
            if messages == "quit":
                print("{} left!".format(clientname))
                broadcast('{} left!'.format(clientname).encode('ascii'), index)
                clientnames.remove(clientname)
                clients.remove(client)
                client.close()
                break
            index = clients.index(client)
            clientname = clientnames[index]
            print("<{}> {}".format(clientname, messages))
            broadcast("({}) {}".format(clientname, messages).encode('ascii'), index)
        except:
            print("Error on receiving")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM