From b9da3e24eb07abcb33932480b8dbbcf69024c614 Mon Sep 17 00:00:00 2001 From: nea Date: Mon, 27 Mar 2023 21:54:37 +0200 Subject: Proper async server and ctrl-c handling --- src/connect.rs | 29 ++++++++++++----------------- 1 file changed, 12 insertions(+), 17 deletions(-) (limited to 'src/connect.rs') diff --git a/src/connect.rs b/src/connect.rs index 82590fb..1feb03e 100644 --- a/src/connect.rs +++ b/src/connect.rs @@ -1,9 +1,9 @@ -use std::net::TcpStream; - use anyhow::Result; -use craftio_rs::{CraftSyncReader, CraftSyncWriter, CraftTcpConnection}; +use craftio_rs::{CraftAsyncReader, CraftAsyncWriter, CraftTokioConnection}; use mcproto_rs::protocol::HasPacketKind; use mcproto_rs::v1_19_3::{Packet761, Packet761Kind, RawPacket761}; +use tokio::io::BufReader; +use tokio::net::TcpStream; #[macro_export] macro_rules! await_packet { @@ -36,24 +36,19 @@ macro_rules! assert_packet { } pub struct MinecraftClient { - pub connection: CraftTcpConnection, + pub connection: CraftTokioConnection, } impl MinecraftClient { - pub fn new(connection: CraftTcpConnection) -> Self { - Self { connection } - } - - pub fn from_stream(stream: TcpStream) -> Result { - Ok(Self { - connection: CraftTcpConnection::from_std( - stream, - mcproto_rs::protocol::PacketDirection::ServerBound, - )?, - }) + pub fn from_stream(stream: TcpStream) -> Self { + let (read, write) = stream.into_split(); + let bufread = BufReader::new(read); + MinecraftClient { + connection: CraftTokioConnection::from_async((bufread, write), mcproto_rs::protocol::PacketDirection::ServerBound), + } } pub async fn read_next_packet(&mut self) -> Result> { - if let Some(raw) = self.connection.read_packet::()? { + if let Some(raw) = self.connection.read_packet_async::().await? { println!("Client -> Server: {:?}", raw); Ok(Some(raw)) } else { @@ -62,7 +57,7 @@ impl MinecraftClient { } pub async fn send_packet(&mut self, packet: Packet761) -> Result<()> { println!("Server -> Client: {:?}", packet); - self.connection.write_packet(packet)?; + self.connection.write_packet_async(packet).await?; Ok(()) } pub async fn wait_for_packet(&mut self, packet_kind: Packet761Kind) -> Result { -- cgit