WIP
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "hd-client"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
@@ -0,0 +1,7 @@
|
||||
use hd_client::{EventBusClient, EventBusClientError};
|
||||
|
||||
fn main() -> Result<(), EventBusClientError> {
|
||||
let addr = "0.0.0.0:21368";
|
||||
let mut client = EventBusClient::start(addr)?;
|
||||
client.subscribe()
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
use std::{
|
||||
io::{Read, Write},
|
||||
net::TcpStream,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum EventBusClientError {
|
||||
TcpStreamError(std::io::Error),
|
||||
}
|
||||
|
||||
pub struct EventBusClient {
|
||||
tcp_stream: TcpStream,
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
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)?;
|
||||
|
||||
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");
|
||||
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)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user