Back
+15 XP
Concept

Asynchronous Sockets with asyncio.open_connection

`asyncio.open_connection(host, port)` opens an asynchronous stream, returning a `StreamReader` and `StreamWriter` without blocking the event loop ⚡.

python
import asyncio

async def fetch_example():
    # Asynchronously connect and stream bytes:
    # reader, writer = await asyncio.open_connection('example.com', 80)
    # writer.write(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
    # await writer.drain()
    # data = await reader.read(1024)
    # writer.close()
    return "Async socket connection established ⚡"

print(asyncio.run(fetch_example()))

# 76. Asynchronous Sockets with asyncio.open_connection `asyncio.open_connection(host, port)` opens an asynchronous stream, returning a `StreamReader` and `StreamWriter` without blocking the event loop ⚡. ```python import asyncio async def fetch_example(): # Asynchronously connect and stream bytes: # reader, writer = await asyncio.open_connection('example.com', 80) # writer.write(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n") # await writer.drain() # data = await reader.read(1024) # writer.close() return "Async socket connection established ⚡" print(asyncio.run(fetch_example())) ``` Always call `await writer.drain()` after `writer.write()`. It pauses execution if the underlying OS network buffer is saturated, preventing memory bloat! ⚡ --- ### Question What tuple of objects does `await asyncio.open_connection()` return? 🧠 - [ ] a. A `(StreamReader, StreamWriter)` pair ⚡ - [ ] b. A `(Socket, Process)` pair - [ ] c. A thread ID integer and socket pointer - [ ] d. A raw integer file descriptor --- ### Challenge Write an async function `dummy_stream()` returning `'Stream Connected'`. Run it with `asyncio.run()` and print the output. 🎯 <details> <summary>Solution</summary> ```python import asyncio async def dummy_stream(): return "Stream Connected" print(asyncio.run(dummy_stream())) ``` </details>

Checkpoint

What tuple of objects does `await asyncio.open_connection()` return? 🧠

Practice

Write an async function `dummy_stream()` returning `'Stream Connected'`. Run it with `asyncio.run()` and print the output. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks