|
| 1 | +import sys |
| 2 | +import asyncio |
| 3 | +import ipaddress |
| 4 | +from ipaddress import IPv4Address, IPv6Address |
| 5 | +import wit_world |
| 6 | +from wit_world import exports |
| 7 | +from wit_world.imports.wasi_sockets_types import ( |
| 8 | + TcpSocket, |
| 9 | + IpSocketAddress_Ipv4, |
| 10 | + IpSocketAddress_Ipv6, |
| 11 | + Ipv4SocketAddress, |
| 12 | + Ipv6SocketAddress, |
| 13 | + IpAddressFamily, |
| 14 | +) |
| 15 | +from typing import Tuple |
| 16 | + |
| 17 | + |
| 18 | +IPAddress = IPv4Address | IPv6Address |
| 19 | + |
| 20 | +class Run(exports.Run): |
| 21 | + async def run(self) -> None: |
| 22 | + args = sys.argv[1:] |
| 23 | + if len(args) != 1: |
| 24 | + print("usage: tcp-p3 <address>:<port>", file=sys.stderr) |
| 25 | + exit(-1) |
| 26 | + |
| 27 | + address, port = parse_address_and_port(args[0]) |
| 28 | + await send_and_receive(address, port) |
| 29 | + |
| 30 | + |
| 31 | +def parse_address_and_port(address_and_port: str) -> Tuple[IPAddress, int]: |
| 32 | + ip, separator, port = address_and_port.rpartition(":") |
| 33 | + assert separator |
| 34 | + return (ipaddress.ip_address(ip.strip("[]")), int(port)) |
| 35 | + |
| 36 | + |
| 37 | +def make_socket_address(address: IPAddress, port: int) -> IpSocketAddress_Ipv4 | IpSocketAddress_Ipv6: |
| 38 | + if isinstance(address, IPv4Address): |
| 39 | + octets = address.packed |
| 40 | + return IpSocketAddress_Ipv4(Ipv4SocketAddress( |
| 41 | + port=port, |
| 42 | + address=(octets[0], octets[1], octets[2], octets[3]), |
| 43 | + )) |
| 44 | + else: |
| 45 | + b = address.packed |
| 46 | + return IpSocketAddress_Ipv6(Ipv6SocketAddress( |
| 47 | + port=port, |
| 48 | + flow_info=0, |
| 49 | + address=( |
| 50 | + (b[0] << 8) | b[1], |
| 51 | + (b[2] << 8) | b[3], |
| 52 | + (b[4] << 8) | b[5], |
| 53 | + (b[6] << 8) | b[7], |
| 54 | + (b[8] << 8) | b[9], |
| 55 | + (b[10] << 8) | b[11], |
| 56 | + (b[12] << 8) | b[13], |
| 57 | + (b[14] << 8) | b[15], |
| 58 | + ), |
| 59 | + scope_id=0, |
| 60 | + )) |
| 61 | + |
| 62 | + |
| 63 | +async def send_and_receive(address: IPAddress, port: int) -> None: |
| 64 | + family = IpAddressFamily.IPV4 if isinstance(address, IPv4Address) else IpAddressFamily.IPV6 |
| 65 | + |
| 66 | + sock = TcpSocket.create(family) |
| 67 | + |
| 68 | + await sock.connect(make_socket_address(address, port)) |
| 69 | + |
| 70 | + send_tx, send_rx = wit_world.byte_stream() |
| 71 | + async def write() -> None: |
| 72 | + with send_tx: |
| 73 | + await send_tx.write_all(b"hello, world!") |
| 74 | + await asyncio.gather(sock.send(send_rx), write()) |
| 75 | + |
| 76 | + recv_rx, recv_fut = sock.receive() |
| 77 | + async def read() -> None: |
| 78 | + with recv_rx: |
| 79 | + data = await recv_rx.read(1024) |
| 80 | + print(f"received: {str(data)}") |
| 81 | + await asyncio.gather(recv_fut.read(), read()) |
0 commit comments