Skip to content

Commit d0044b4

Browse files
Add aiohttp websocket code
1 parent f53ae98 commit d0044b4

File tree

1 file changed

+46
-0
lines changed
  • apps/com.example.wstest/assets

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# import mip
2+
# mip.install(aiohttp)
3+
4+
import sys
5+
import ssl
6+
7+
# ruff: noqa: E402
8+
sys.path.insert(0, ".")
9+
import aiohttp
10+
import asyncio
11+
12+
try:
13+
URL = sys.argv[1] # expects a websocket echo server
14+
except Exception:
15+
URL = "ws://echo.websocket.events"
16+
17+
18+
sslctx = False
19+
20+
if URL.startswith("wss:"):
21+
try:
22+
sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
23+
sslctx.verify_mode = ssl.CERT_NONE
24+
except Exception:
25+
pass
26+
27+
28+
async def ws_test_echo(session):
29+
async with session.ws_connect(URL, ssl=sslctx) as ws:
30+
await ws.send_str("hello world!\r\n")
31+
async for msg in ws:
32+
if msg.type == aiohttp.WSMsgType.TEXT:
33+
print(msg.data)
34+
if "close" in msg.data:
35+
break
36+
await ws.send_str("close\r\n")
37+
await ws.close()
38+
39+
40+
async def main():
41+
async with aiohttp.ClientSession() as session:
42+
await ws_test_echo(session)
43+
44+
45+
if __name__ == "__main__":
46+
asyncio.run(main())

0 commit comments

Comments
 (0)