python3.6 websocket异步高并发_在Python3.6上的websocket客户端中侦听传入消息时出现问题...
我正在嘗試使用websockets包在Python上構(gòu)建一個(gè)websockets客戶(hù)端:Websockets 4.0 API
我使用這種方式而不是示例代碼,因?yàn)槲蚁雱?chuàng)建一個(gè)websocket客戶(hù)機(jī)類(lèi)對(duì)象,并將其用作網(wǎng)關(guān)。在
我在客戶(hù)端的偵聽(tīng)器方法(receiveMessage)有問(wèn)題,這會(huì)在執(zhí)行時(shí)引發(fā)ConnectionClose異常。我想也許這個(gè)循環(huán)有什么問(wèn)題。在
這是我嘗試構(gòu)建的簡(jiǎn)單webSocket客戶(hù)端:import websockets
class WebSocketClient():
def __init__(self):
pass
async def connect(self):
'''
Connecting to webSocket server
websockets.client.connect returns a WebSocketClientProtocol, which is used to send and receive messages
'''
self.connection = await websockets.client.connect('ws://127.0.0.1:8765')
if self.connection.open:
print('Connection stablished. Client correcly connected')
# Send greeting
await self.sendMessage('Hey server, this is webSocket client')
# Enable listener
await self.receiveMessage()
async def sendMessage(self, message):
'''
Sending message to webSocket server
'''
await self.connection.send(message)
async def receiveMessage(self):
'''
Receiving all server messages and handling them
'''
while True:
message = await self.connection.recv()
print('Received message from server: ' + str(message))
這是主要的:
^{pr2}$
為了測(cè)試傳入消息偵聽(tīng)器,服務(wù)器在建立連接時(shí)向客戶(hù)端發(fā)送兩條消息。在
客戶(hù)端正確連接到服務(wù)器,并發(fā)送問(wèn)候語(yǔ)。然而,當(dāng)客戶(hù)機(jī)接收到這兩條消息時(shí),它會(huì)引發(fā)一個(gè)ConnectionClosed異常,代碼為1000(沒(méi)有原因)。在
如果刪除receiveMessage客戶(hù)機(jī)方法中的循環(huán),則客戶(hù)機(jī)不會(huì)引發(fā)任何異常,但它只接收一條消息,所以我想我需要一個(gè)循環(huán)來(lái)保持偵聽(tīng)器的活動(dòng),但我不知道確切的位置和方式。在
有什么解決辦法嗎?在
提前謝謝。在
編輯:我意識(shí)到,當(dāng)客戶(hù)端從服務(wù)器接收到所有掛起的消息時(shí),它會(huì)關(guān)閉連接(并中斷循環(huán))。不過(guò),我希望客戶(hù)能繼續(xù)收聽(tīng)未來(lái)的消息。在
此外,我還嘗試添加另一個(gè)函數(shù),其任務(wù)是向服務(wù)器發(fā)送“heartbeat”,但客戶(hù)端還是關(guān)閉了連接。在
總結(jié)
以上是生活随笔為你收集整理的python3.6 websocket异步高并发_在Python3.6上的websocket客户端中侦听传入消息时出现问题...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: FPL 2017最佳论文:如何对FPGA
- 下一篇: 我的第一个python web开发框架(