2017-02-14 268 views
1

使用Python v3.5或v3.6當連接到某些websocket服務器時,websocket客戶端不關閉。下面的示例代碼顯示了當連接到wss://echo.websocket.org時該進程正常工作,但在連接到wss:/stream.pushbullet.com時未能斷開連接。aiohttp Websocket在連接到某些websocket服務器時不關閉

任何人都可以看到有什麼區別?幾乎看起來它應該與服務器有關,以及它如何表現(或者可能是行爲不當)。

import asyncio 
import aiohttp 

# Code: http://pastebin.com/G5sfpQG2 
# Closing the echo.websocket.org connection works as expected 
# Closing the stream.pushbullet.com connection hangs 

async def run(): 
    session = aiohttp.ClientSession() 
    API_KEY = "RrFnc1xaeQXnRrr2auoGA1e8pQ8MWmMF" # (OK to have here) 
    async with session.ws_connect('wss://stream.pushbullet.com/websocket/' + API_KEY) as ws: 
    # async with session.ws_connect("wss://echo.websocket.org") as ws: 
     ws.send_json({"hello": "world"}) 

     async def _timeout(): 
      await asyncio.sleep(2) 
      print('closing ... ', end="", flush=True) 
      await ws.close() 
      print('... closed. Should see "broke out of ..." messages next') 

     asyncio.get_event_loop().create_task(_timeout()) 

     async for ws_msg in ws: 
      print("ws_msg:", ws_msg) 

     print("broke out of async for loop") 
    print("broke out of async with") 
    session.close() 

loop = asyncio.get_event_loop() 
loop.run_until_complete(run()) 
print("goodbye") 

回答

0

嘆息 aiohttp的1.3.0版修復了這個。我會認爲這是一個錯誤。我在v1.2.0上。

-Rob

1

雖然用戶已經回答了這個問題,我發現沒有關閉套接字,服務器的問題仍然普遍存在於aiohttp 2.0爲好。

很多次這是服務器的問題!調試後發現有些服務器不按照協議關閉ssl連接。對於這樣的服務器,在創建connector對象時添加以下參數通常可以完成這項工作。

force_close=True, enable_cleanup_closed=True 

爲在2.0上可能仍然面臨此問題的用戶添加此信息。

+0

這不提供問題的答案。一旦你有足夠的[聲譽](https://stackoverflow.com/help/whats-reputation),你將可以[對任何帖子發表評論](https://stackoverflow.com/help/privileges/comment);相反,[提供不需要提問者澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an- I-DO-代替)。 - [來自評論](/ review/low-quality-posts/16737768) – kdopen

相關問題