Send keep alive packets every 10s

This commit is contained in:
Garen Tyler 2021-03-17 21:28:02 -06:00
parent 6fa9ee968e
commit a0e355ddde
4 changed files with 126 additions and 39 deletions

View File

@ -257,13 +257,7 @@ pub mod other {
}
impl Display for MCPosition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"({}, {}, {})",
self.x,
self.y,
self.z,
)
write!(f, "({}, {}, {})", self.x, self.y, self.z,)
}
}
impl TryFrom<Vec<u8>> for MCPosition {
@ -279,13 +273,10 @@ pub mod other {
let mut out = vec![];
let mut temp = vec![];
temp.extend_from_slice(
&(
(
((Into::<i64>::into(self.x) & 0x3FFFFFF) << 38)
&((((Into::<i64>::into(self.x) & 0x3FFFFFF) << 38)
| ((Into::<i64>::into(self.y) & 0xFFF) << 26)
| (Into::<i64>::into(self.z) & 0x3FFFFFF)
) as u64
).to_be_bytes()
| (Into::<i64>::into(self.z) & 0x3FFFFFF)) as u64)
.to_be_bytes(),
);
// temp.extend_from_slice(&"{\"text\": \"".to_owned().into_bytes());
// temp.extend_from_slice(&self.text.value.into_bytes());

View File

@ -7,6 +7,7 @@ use log::{debug, info};
use packets::*;
use serde_json::json;
use std::sync::mpsc::{self, Receiver, TryRecvError};
use std::time::{Duration, Instant};
use tokio::net::{TcpListener, TcpStream, ToSocketAddrs};
/// The struct containing all the data and running all the updates.
@ -101,6 +102,7 @@ pub struct NetworkClient {
pub state: NetworkClientState,
pub uuid: Option<String>,
pub username: Option<String>,
pub last_keep_alive: Instant,
}
impl NetworkClient {
/// Create a new `NetworkClient`
@ -112,6 +114,7 @@ impl NetworkClient {
state: NetworkClientState::Handshake,
uuid: None,
username: None,
last_keep_alive: Instant::now(),
}
}
@ -237,16 +240,35 @@ impl NetworkClient {
let spawnposition = SpawnPosition::new();
spawnposition.write(&mut self.stream).await.unwrap();
debug!("{:?}", spawnposition);
// Send initial keep alive.
self.keep_alive().await;
// TODO: S->C Player Position and Look
// TODO: C->S Teleport Confirm
// TODO: C->S Player Position and Look
// TODO: C->S Client Status
// TODO: S->C inventories, entities, etc.
}
NetworkClientState::Play => {}
NetworkClientState::Play => {
if self.last_keep_alive.elapsed() > Duration::from_secs(10) {
self.keep_alive().await;
}
}
NetworkClientState::Disconnected => {
self.connected = false;
}
}
}
/// Send a keep alive packet to the client.
async fn keep_alive(&mut self) {
// Keep alive ping to client.
let clientboundkeepalive = KeepAlivePing::new();
clientboundkeepalive.write(&mut self.stream).await.unwrap();
debug!("{:?}", clientboundkeepalive);
// Keep alive pong to server.
let (_packet_length, _packet_id) = read_packet_header(&mut self.stream).await.unwrap();
let serverboundkeepalive = KeepAlivePong::read(&mut self.stream).await.unwrap();
debug!("{:?}", serverboundkeepalive);
self.last_keep_alive = Instant::now();
}
}

View File

@ -432,3 +432,40 @@ impl SpawnPosition {
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct KeepAlivePing {
payload: MCVarInt,
}
impl Into<Vec<u8>> for KeepAlivePing {
fn into(self) -> Vec<u8> {
let mut out = vec![];
let mut temp: Vec<u8> = MCVarInt::from(0x00).into(); // 0x00 Keep Alive.
temp.extend_from_slice(&Into::<Vec<u8>>::into(self.payload));
out.extend_from_slice(&Into::<Vec<u8>>::into(MCVarInt::from(temp.len() as i32)));
out.extend_from_slice(&temp);
out
}
}
impl TryFrom<Vec<u8>> for KeepAlivePing {
type Error = &'static str;
fn try_from(_bytes: Vec<u8>) -> Result<Self, Self::Error> {
Err("unimplemented")
}
}
impl KeepAlivePing {
pub fn new() -> Self {
KeepAlivePing { payload: 0.into() }
}
pub async fn read(t: &mut TcpStream) -> tokio::io::Result<Self> {
let mut keepalive = KeepAlivePing::new();
keepalive.payload = MCVarInt::read(t).await?;
Ok(keepalive)
}
pub async fn write(&self, t: &mut TcpStream) -> tokio::io::Result<()> {
for b in Into::<Vec<u8>>::into(self.clone()) {
write_byte(t, b).await?;
}
Ok(())
}
}

View File

@ -225,3 +225,40 @@ impl ClientSettings {
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct KeepAlivePong {
payload: MCVarInt,
}
impl Into<Vec<u8>> for KeepAlivePong {
fn into(self) -> Vec<u8> {
let mut out = vec![];
let mut temp: Vec<u8> = MCVarInt::from(0x00).into(); // 0x00 Keep Alive.
temp.extend_from_slice(&Into::<Vec<u8>>::into(self.payload));
out.extend_from_slice(&Into::<Vec<u8>>::into(MCVarInt::from(temp.len() as i32)));
out.extend_from_slice(&temp);
out
}
}
impl TryFrom<Vec<u8>> for KeepAlivePong {
type Error = &'static str;
fn try_from(_bytes: Vec<u8>) -> Result<Self, Self::Error> {
Err("unimplemented")
}
}
impl KeepAlivePong {
pub fn new() -> Self {
KeepAlivePong { payload: 0.into() }
}
pub async fn read(t: &mut TcpStream) -> tokio::io::Result<Self> {
let mut keepalive = KeepAlivePong::new();
keepalive.payload = MCVarInt::read(t).await?;
Ok(keepalive)
}
pub async fn write(&self, t: &mut TcpStream) -> tokio::io::Result<()> {
for b in Into::<Vec<u8>>::into(self.clone()) {
write_byte(t, b).await?;
}
Ok(())
}
}