下面是我創造我在程序的線程的基本概念:添加time.sleep到多線程程序解決了的UnicodeDecodeError在python
Main thread
|
ListenerCreator(The WebSocketServer thread) ---> Several listener threads(using log())
所以主線程創建一個線程ListenerCreator,連接到多個客戶端併爲每個客戶端創建一個偵聽器線程。下面簡要介紹一下監聽線程的功能: EDIT1: 我使用WebSockets從我的客戶端讀取/寫入數據。爲此我創建了自己的服務器。有一個標準規定的framing protocol - 我正在使用它。在客戶端,我簡單地使用WebSocket.send()並根據協議中給出的指令「解除掩碼」(參見上面鏈接中的第5.3節)。 如果有人請求它,我願意提供服務器代碼,但是,這裏有一個簡要介紹:
class WebSocketServer:
def start():
#Open server socket, bind to host:port
while True:
#Accept client socket, start a new listener thread for self.log(client)
def log(client):
#Receive data using socket.socket.recv(1024)
#Unmask data as per the protocol
#Decode using data.decode("utf-8")
#Append to data_q while holding data_q_lock
還有其他的方法 - 那些便於發,關閉,握手等。
同時在主線程:
while breaking!=len(client_list):
#time.sleep(0.5)
with data_q_lock:
for i in range(len(data_q)):
mes = data_q.pop()
for m in client_list:
if "#DONE"== mes:
breaking += 1
if(mes[:len("#COUNT:")] == "#COUNT:"):
print(mes)
所以基本上這個循環中所做的是:環通的data_q,如果消息與「#COUNT」開始,打印郵件,並獲得一定數量後「#DONE」消息,退出循環。 如果time.sleep未註釋,則此代碼有效,但無time.sleep,我在日誌函數中收到UnicodeDecodeError。 此外,我只得到錯誤有時,有時程序完美。 (順便說一句,客戶端每次都發送相同的數據) 所以,我的問題是,爲什麼需要time.sleep? 我認爲這是與python中的GIL有關,因爲time.sleep釋放GIL。但是,即使在閱讀後我仍無法解決問題
請說明如何從監聽器中的套接字讀取數據,它與您的問題非常相關:-) – donkopotamus