Initial protocol

This commit is contained in:
2026-09-08 19:30:24 +05:30
parent 6a62c33f42
commit a3385e7702
9 changed files with 236 additions and 145 deletions
+1
View File
@@ -6,3 +6,4 @@ edition = "2024"
[dependencies]
tracing = { workspace = true }
hd-lib = { path = "../hd-lib" }
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
+4
View File
@@ -1,6 +1,10 @@
use hd_client::{EventBusClient, EventBusClientError};
fn main() -> Result<(), EventBusClientError> {
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.init();
let addr = "0.0.0.0:21368";
let mut client = EventBusClient::start(addr)?;
client.subscribe()
+26 -30
View File
@@ -1,11 +1,22 @@
use std::{
io::{Read, Write},
net::TcpStream,
use std::net::TcpStream;
use hd_lib::{
bus::packet::{self, Packet, PacketType},
error::HError,
hd_tcp,
};
use tracing::{debug, info};
#[derive(Debug)]
pub enum EventBusClientError {
TcpStreamError(std::io::Error),
HError(HError),
}
impl From<HError> for EventBusClientError {
fn from(value: HError) -> Self {
Self::HError(value)
}
}
pub struct EventBusClient {
@@ -14,43 +25,28 @@ pub struct EventBusClient {
impl EventBusClient {
pub fn start(addr: &'static str) -> Result<Self, EventBusClientError> {
let stream = TcpStream::connect(addr).map_err(EventBusClientError::TcpStreamError)?;
println!("Event bus client connected to {}", addr);
let mut stream = TcpStream::connect(addr).map_err(EventBusClientError::TcpStreamError)?;
hd_tcp::write_packet(&mut stream, &Packet::create_connect_packet())?;
hd_tcp::read_ack(&mut stream, &[PacketType::Connect])?;
info!("Event bus client connected to {}", addr);
Ok(Self { tcp_stream: stream })
}
pub fn subscribe(&mut self) -> Result<(), EventBusClientError> {
let bytes = [1];
self.tcp_stream
.write_all(&bytes)
.map_err(EventBusClientError::TcpStreamError)?;
debug!("Going to subscribe");
hd_tcp::write_packet(&mut self.tcp_stream, &Packet::create_subscribe_packet(0))?;
hd_tcp::read_ack(&mut self.tcp_stream, &[PacketType::Subscribe])?;
self.tcp_stream.flush().map_err(EventBusClientError::TcpStreamError)?;
let mut buf = vec![0; 1024];
loop {
let Ok(bytes_read) = self.tcp_stream.read(&mut buf) else {
return Ok(());
};
if bytes_read == 0 {
eprintln!("Connection closed");
let packet = hd_tcp::read_packet(&mut self.tcp_stream)?;
if let Packet::Disconnect = packet {
info!("Disconnecting from the server");
return Ok(());
}
println!("MESSAGE BEGIN");
for b in &buf[0..bytes_read] {
print!("[{}] ", b);
}
println!("MESSAGE END");
// ACK
self.tcp_stream
.write_all(&bytes)
.map_err(EventBusClientError::TcpStreamError)?;
self.tcp_stream.flush().map_err(EventBusClientError::TcpStreamError)?;
debug!("Received packet ... {}", packet::get_packet_type(&packet));
hd_tcp::write_ack(&mut self.tcp_stream, PacketType::SendEvent)?;
}
}
}