json works

This commit is contained in:
clizia 2025-02-20 11:17:40 +01:00
parent 2e3c3f9fff
commit cbf63fabd5
5 changed files with 22 additions and 96 deletions

View file

@ -9,30 +9,19 @@ use crossterm::{
}, },
event::Event, event::Event,
}; };
use std::io::{self, Write};
#[tokio::main] #[tokio::main]
pub async fn main() -> anyhow::Result<()> { pub async fn main() -> anyhow::Result<()> {
let mut client = Client::connect("127.0.0.1", 8080).await?; let mut client = Client::connect("127.0.0.1", 8080).await?;
let local_address = &client.stream.local_addr()?;
enable_raw_mode()?; enable_raw_mode()?;
execute!( execute!(
io::stdout(), std::io::stdout(),
Clear(ClearType::All), Clear(ClearType::All),
)?; )?;
'get_instruction: loop { client.send_message(Message::new(&local_address.to_string(), MessageKind::Test, "test json").unwrap()).await?;
match TODO {
todo!()
}
}
for i in 1..11 {
let message = Message::new(lib::message::MessageKind::Move, format!("Hello toto x {}!!!", i));
client.send_message(message.unwrap().clone()).await?;
}
client.send_message(Message::new(MessageKind::Move, "EXIT").unwrap()).await?;
disable_raw_mode()?; disable_raw_mode()?;
Ok(()) Ok(())

View file

@ -22,7 +22,8 @@ impl Client {
} }
pub async fn send_message(&mut self, message: Message) -> anyhow::Result<()> { pub async fn send_message(&mut self, message: Message) -> anyhow::Result<()> {
self.stream.write_all(&message.encode()).await?; let message_string = message.encode()?;
self.stream.write_all(&message_string.as_bytes()).await?;
Ok(()) Ok(())
} }

View file

@ -1,10 +1,5 @@
use anyhow::Ok;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
// use crate::constant::{MESSAGE_KIND_CREATE_LOBBY, MESSAGE_KIND_CREATE_PLAYER, MESSAGE_KIND_MOVE, METADATA_SIZE};
// everything here needs to be adjusted for the deserialized json
//
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message { pub struct Message {
pub from: String, pub from: String,
@ -13,9 +8,9 @@ pub struct Message {
pub content: String, pub content: String,
} }
// idk i just want to layout something, really didn't think much
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MessageKind { pub enum MessageKind {
Test,
Move, Move,
CreatePlayer, CreatePlayer,
CreateLobby, CreateLobby,
@ -36,47 +31,14 @@ impl Message {
} }
pub fn encode(&self) -> anyhow::Result<String> { pub fn encode(&self) -> anyhow::Result<String> {
// let mut buffer = Vec::new();
// buffer.extend(self.from.as_bytes());
// buffer.extend()
// buffer.extend(&self.length.to_be_bytes());
// buffer.extend(self.content.as_bytes());
let message_json: String = serde_json::to_string(self)?; let message_json: String = serde_json::to_string(self)?;
Ok(message_json) Ok(message_json)
} }
pub fn decode(buffer: &[u8]) -> anyhow::Result<Self> { pub fn decode(buffer: &[u8]) -> anyhow::Result<Self> {
// if buffer.len() < METADATA_SIZE {
// return Err(anyhow::anyhow!("Invalid message length"));
// }
// let message_kind = MessageKind::try_from(buffer[0]).expect("Error parsing the MessageKind");
// let length = u16::from_be_bytes([buffer[1], buffer[2]]);
// let content = String::from_utf8(buffer[3..3 + length as usize].to_vec())?;
// Ok(Self {
// message_kind,
// length,
// content,
// })
let message: Message = serde_json::from_slice(buffer)?; let message: Message = serde_json::from_slice(buffer)?;
Ok(message) Ok(message)
} }
} }
// impl TryFrom<u8> for MessageKind {
// type Error = &'static str;
// fn try_from(value: u8) -> Result<Self, Self::Error> {
// match value {
// MESSAGE_KIND_MOVE => Ok(MessageKind::Move),
// MESSAGE_KIND_CREATE_PLAYER => Ok(MessageKind::CreatePlayer),
// MESSAGE_KIND_CREATE_LOBBY => Ok(MessageKind::CreateLobby),
// _ => Err("invalid MessageKind byte")
// }
// }
// }

View file

@ -1,6 +1,7 @@
// add message kind everywhere is needed use crate::message::Message;
use crate::{constant::METADATA_SIZE, message::Message};
// this won't be needed in the near future, i want
// to do everything within Message
pub struct MessageReader { pub struct MessageReader {
pub buffer: Vec<u8>, pub buffer: Vec<u8>,
} }
@ -10,33 +11,10 @@ impl MessageReader {
Self { buffer: Vec::new() } Self { buffer: Vec::new() }
} }
fn can_parse(&self) -> bool { pub fn read(&mut self, data: &[u8]) -> anyhow::Result<Message> {
if self.buffer.len() < METADATA_SIZE {
return false;
}
let length = u16::from_be_bytes([self.buffer[0], self.buffer[1]]);
self.buffer.len() >= METADATA_SIZE + length as usize
}
fn parse_first(&mut self) -> anyhow::Result<Message> {
let length = u16::from_be_bytes([self.buffer[0], self.buffer[1]]);
let message_length = METADATA_SIZE + length as usize;
let message = self.buffer[..message_length].to_vec();
self.buffer = self.buffer[message_length..].to_vec();
Message::decode(&message)
}
pub fn read(&mut self, data: &[u8]) -> anyhow::Result<Vec<Message>> {
self.buffer.extend_from_slice(data); self.buffer.extend_from_slice(data);
let mut data = vec![]; let message = serde_json::from_slice(&self.buffer)?;
while self.can_parse() { Ok(message)
let message = self.parse_first()?;
data.push(message);
}
Ok(data)
} }
} }

View file

@ -1,4 +1,4 @@
use tokio::{io::AsyncReadExt, net::TcpListener}; use tokio::{io::{AsyncReadExt, AsyncWriteExt}, net::TcpListener};
use std::net::SocketAddr; use std::net::SocketAddr;
use crate::{message::Message, message_read::MessageReader}; use crate::{message::Message, message_read::MessageReader};
@ -31,22 +31,18 @@ impl Server {
tokio::task::spawn(async move { tokio::task::spawn(async move {
let mut message_reader = MessageReader::new(); let mut message_reader = MessageReader::new();
let (mut read, mut write) = socket.split(); let (mut rd, mut wr) = socket.split();
'handler: loop { 'handler: loop {
let mut buffer = vec![0; 256]; let mut buffer = vec![];
let bytes_read = read.read(&mut buffer).await?; if tokio::io::copy(&mut rd, &mut buffer).await.is_err() {
eprintln!("failed to copy");
let messages = message_reader.read(&buffer[..bytes_read])?;
for message in messages {
if message.content == "EXIT" {
println!("Connection closed by the client");
break 'handler;
}
println!("Message:\n{:?}", message);
} }
let message = message_reader.read(&buffer)?;
println!("{:?}", message.content);
break 'handler;
} }
Ok::<(), anyhow::Error>(()) Ok::<(), anyhow::Error>(())