using standardized tcp requests and responses

This commit is contained in:
2026-08-16 15:41:18 +02:00
parent 0b3853e1be
commit 673eed4e80
3 changed files with 113 additions and 46 deletions
+33 -15
View File
@@ -3,36 +3,54 @@ use ringbuf::{
HeapRb, HeapRb,
traits::{Consumer, Observer, Producer, Split}, traits::{Consumer, Observer, Producer, Split},
}; };
use shared::{ConectionResponse, ResponseStatus}; use shared::{ResponseStatus, TcpRequest, TcpResponse, TcpResponseData};
use std::sync::Arc; use std::sync::Arc;
use tokio::net::{TcpStream, UdpSocket}; use tokio::{
io::AsyncWriteExt,
net::{TcpStream, UdpSocket},
};
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
let server_address = "127.0.0.1:8080"; let server_address = "127.0.0.1:8080";
let tcp_stream = TcpStream::connect(server_address) let mut tcp_stream = TcpStream::connect(server_address)
.await .await
.expect("failed to connect using tcp"); .expect("failed to connect using tcp");
let _ = tcp_stream
.write_all(
serde_json::to_string(&TcpRequest {
client_id: 0,
data: shared::TcpRequestData::NewConnection,
})
.expect("failed to parse initial request")
.as_bytes(),
)
.await
.expect("failed to send initial message");
tcp_stream.readable().await.expect("idk"); tcp_stream.readable().await.expect("idk");
let mut tcp_buf = [0; 4096]; let mut tcp_buf = [0; 4096];
let mut session_client_id: u32 = 0; let mut session_client_id: u32 = 0;
match tcp_stream.try_read(&mut tcp_buf) { match tcp_stream.try_read(&mut tcp_buf) {
Ok(n) => { Ok(n) => match serde_json::from_slice::<TcpResponse>(&tcp_buf[0..n]) {
let connection_response: ConectionResponse = Ok(response) => {
serde_json::from_slice(&tcp_buf[0..n]).unwrap(); println!("connection Ok: {}", response.status == ResponseStatus::Ok);
match response.data {
session_client_id = connection_response.client_id; TcpResponseData::NewConnection { client_id } => {
session_client_id = client_id;
println!( println!("new client id: {}", client_id)
"tcp response status Ok: {}, clientId: {}",
connection_response.status == ResponseStatus::Ok,
connection_response.client_id
);
} }
_ => {
println!("wrong response")
}
}
}
Err(e) => eprintln!("failed to parse tcp packet: {}", e),
},
Err(e) => eprintln!("failed to receive tcp packet: {}", e), Err(e) => eprintln!("failed to receive tcp packet: {}", e),
} }
@@ -133,7 +151,7 @@ async fn main() {
} }
let id_bytes: [u8; 4] = receive_buffer[0..4].try_into().unwrap(); let id_bytes: [u8; 4] = receive_buffer[0..4].try_into().unwrap();
let client_id = u32::from_be_bytes(id_bytes); let stream_id = u32::from_be_bytes(id_bytes);
let audio_packet = &receive_buffer[4..len]; let audio_packet = &receive_buffer[4..len];
+25 -16
View File
@@ -1,4 +1,4 @@
use shared::{ConectionResponse, ResponseStatus}; use shared::{AudioStreamInfo, ResponseStatus, TcpRequest, TcpRequestData, TcpResponse};
use std::sync::Arc; use std::sync::Arc;
use std::{collections::HashMap, net::SocketAddr}; use std::{collections::HashMap, net::SocketAddr};
use tokio::io::AsyncWriteExt; use tokio::io::AsyncWriteExt;
@@ -10,6 +10,7 @@ use tokio::{
struct Client { struct Client {
tcp_addr: SocketAddr, tcp_addr: SocketAddr,
udp_addr: Option<SocketAddr>, udp_addr: Option<SocketAddr>,
audio_streams: Option<Vec<AudioStreamInfo>>,
} }
type State = Arc<RwLock<HashMap<u32, Client>>>; type State = Arc<RwLock<HashMap<u32, Client>>>;
@@ -66,34 +67,42 @@ async fn main() {
let (mut tcp_stream, tcp_address) = let (mut tcp_stream, tcp_address) =
tcp_listener.accept().await.expect("failed to accept tcp"); tcp_listener.accept().await.expect("failed to accept tcp");
tcp_stream.readable().await.expect("idk");
let mut tcp_buf = [0; 4096];
match tcp_stream.try_read(&mut tcp_buf) {
Ok(n) => match serde_json::from_slice::<TcpRequest>(&tcp_buf[0..n]) {
Ok(request) => match request.data {
TcpRequestData::NewConnection => {
let client_id = next_client_id; let client_id = next_client_id;
next_client_id += 1; next_client_id += 1;
tcp_state.write().await.insert( tcp_state.write().await.insert(
client_id, client_id,
Client { Client {
tcp_addr: tcp_address, tcp_addr: tcp_address,
udp_addr: None, udp_addr: None,
audio_streams: None,
}, },
); );
println!("new client: {}, from: {}", client_id, tcp_address);
let welcome_msg = ConectionResponse {
status: ResponseStatus::Ok,
client_id: client_id,
};
let _ = tcp_stream let _ = tcp_stream
.write_all( .write_all(
serde_json::to_string(&welcome_msg) serde_json::to_string(&TcpResponse {
.expect("failed to parse json") status: ResponseStatus::Ok,
data: shared::TcpResponseData::NewConnection {
client_id: client_id,
},
})
.expect("failed to parse response json")
.as_bytes(), .as_bytes(),
) )
.await; .await;
}
println!( _ => eprintln!("i dont support other requests yet"),
"new client: {}, from: {}", },
client_id, Err(e) => eprintln!("failed to parse tcp packet: {}", e),
tcp_state.read().await.get(&client_id).unwrap().tcp_addr },
); Err(e) => eprintln!("failed to receive tcp packet: {}", e),
}
} }
} }
+42 -2
View File
@@ -7,7 +7,47 @@ pub enum ResponseStatus {
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct ConectionResponse { pub struct AudioStreamInfo {
pub stream_id: u32,
pub channels: u8,
pub sample_rate: u32,
}
#[derive(Serialize, Deserialize)]
pub struct TcpRequest {
pub client_id: u32,
pub data: TcpRequestData,
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum TcpRequestData {
NewConnection,
DropConnection,
NewAudioStream { audio_stream_info: AudioStreamInfo },
DropAudioStream { audio_stream_id: u32 },
}
#[derive(Serialize, Deserialize)]
pub struct TcpResponse {
pub status: ResponseStatus, pub status: ResponseStatus,
pub client_id: u32, pub data: TcpResponseData,
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum TcpResponseData {
NewConnection {
client_id: u32,
},
Updated,
UserJoined {
user_id: u32,
},
UserDisconnected {
user_id: u32,
},
AudioStreamsUpdate {
audio_stream_info: Vec<AudioStreamInfo>,
},
} }