11use std:: error:: Error ;
2- use wtransport:: { endpoint:: IncomingSession , Endpoint , Identity , ServerConfig } ;
2+ use wtransport:: { config :: TlsClientConfig , endpoint:: IncomingSession , ClientConfig , Endpoint , Identity , ServerConfig } ;
33
44pub async fn start_webtransport ( ) -> Result < ( ) , Box < dyn Error > > {
55 let identity = match Identity :: load_pemfiles ( "certs/localhost.crt" , "certs/localhost.key" ) . await {
@@ -56,11 +56,66 @@ async fn handle_connection(incoming_session: IncomingSession) -> Result<(), Box<
5656
5757 log:: info!( "Accepted connection from {:?}" , connection. remote_address( ) ) ;
5858
59- while let Ok ( ( mut recv_stream , mut send_stream ) ) = connection. accept_bi ( ) . await {
59+ while let Ok ( ( mut send_stream , mut recv_stream ) ) = connection. accept_bi ( ) . await {
6060 log:: trace!( "Accepted bidirectional stream" ) ;
6161
6262 let mut buffer = vec ! [ 0 ; 1024 ] ;
63+ let bytes_read = match recv_stream. read ( & mut buffer) . await {
64+ Ok ( Some ( bytes_read) ) => bytes_read,
65+ Ok ( None ) => {
66+ log:: info!( "Stream closed" ) ;
67+ break ;
68+ }
69+ Err ( e) => {
70+ log:: error!( "Failed to read from stream: {:?}" , e) ;
71+ break ;
72+ }
73+ } ;
74+
75+ log:: info!( "Received data! {:?}" , & buffer[ ..bytes_read] ) ;
76+
77+ match send_stream. write_all ( & buffer[ ..bytes_read] ) . await {
78+ Ok ( _) => { } ,
79+ Err ( e) => {
80+ log:: error!( "Failed to write to stream: {:?}" , e) ;
81+ break ;
82+ }
83+ } ;
84+ } ;
85+
86+ Ok ( ( ) )
87+ }
88+
89+ pub async fn start_client ( ) -> Result < ( ) , Box < dyn Error > > {
90+ let config = ClientConfig :: default ( ) ;
91+
92+ let client = match Endpoint :: client ( config) {
93+ Ok ( client) => client,
94+ Err ( e) => {
95+ log:: error!( "Failed to create client: {:?}" , e) ;
96+ return Err ( Box :: new ( e) ) ;
97+ }
98+ } ;
99+
100+ let connection = match client. connect ( "https://localhost:4433" ) . await {
101+ Ok ( connection) => connection,
102+ Err ( e) => {
103+ log:: error!( "Failed to connect to server: {:?}" , e) ;
104+ return Err ( Box :: new ( e) ) ;
105+ }
63106 } ;
64107
108+ log:: info!( "Connected to server at {:?}" , connection. remote_address( ) ) ;
109+
110+ let ( mut send_stream, mut recv_stream) = connection. open_bi ( ) . await . unwrap ( ) . await . unwrap ( ) ;
111+
112+ let message = b"Hello, world!" ;
113+ send_stream. write_all ( message) . await ?;
114+ log:: info!( "Sent message: {:?}" , message) ;
115+
116+ let mut buffer = vec ! [ 0 ; 1024 ] ;
117+ let bytes_read = recv_stream. read ( & mut buffer) . await . unwrap ( ) . unwrap ( ) ;
118+ log:: info!( "Received data: {:?}" , & buffer[ ..bytes_read] ) ;
119+
65120 Ok ( ( ) )
66121}
0 commit comments