1# Copyright 2021-2022 Google LLC 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# https://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15# ----------------------------------------------------------------------------- 16# Imports 17# ----------------------------------------------------------------------------- 18import asyncio 19import logging 20 21from .common import Transport, StreamPacketSource, StreamPacketSink 22 23# ----------------------------------------------------------------------------- 24# Logging 25# ----------------------------------------------------------------------------- 26logger = logging.getLogger(__name__) 27 28 29# ----------------------------------------------------------------------------- 30async def open_tcp_client_transport(spec: str) -> Transport: 31 ''' 32 Open a TCP client transport. 33 The parameter string has this syntax: 34 <remote-host>:<remote-port> 35 36 Example: 127.0.0.1:9001 37 ''' 38 39 class TcpPacketSource(StreamPacketSource): 40 def connection_lost(self, exc): 41 logger.debug(f'connection lost: {exc}') 42 self.on_transport_lost() 43 44 remote_host, remote_port = spec.split(':') 45 tcp_transport, packet_source = await asyncio.get_running_loop().create_connection( 46 TcpPacketSource, 47 host=remote_host, 48 port=int(remote_port), 49 ) 50 packet_sink = StreamPacketSink(tcp_transport) 51 52 return Transport(packet_source, packet_sink) 53