bincode gaming
This commit is contained in:
@@ -3,7 +3,10 @@ use len_fns::*;
|
||||
|
||||
use crate::{
|
||||
client::{Client, app::AppHandle},
|
||||
net::client::{NetCmd, NetSender, connect},
|
||||
net::{
|
||||
ClientMsg,
|
||||
client::{NetSender, connect},
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Eq, PartialEq, Hash, Clone)]
|
||||
@@ -117,7 +120,11 @@ pub fn msg_panel(ui: &mut Ui, network: NetSender) -> impl WidgetFn<Stack> + use<
|
||||
.clone()
|
||||
.id_on(Submit, move |id, client: &mut Client, _| {
|
||||
let content = client.ui.text(id).take();
|
||||
network.send(NetCmd::SendMsg(content.clone())).unwrap();
|
||||
network
|
||||
.send(ClientMsg::SendMsg {
|
||||
content: content.clone(),
|
||||
})
|
||||
.unwrap();
|
||||
let msg = msg_widget(content).add(&mut client.ui);
|
||||
client.ui[&msg_area].children.push(msg.any());
|
||||
})
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
use crate::{
|
||||
client::{AppHandle, ClientEvent},
|
||||
net::{SERVER_NAME, no_cert::SkipServerVerification},
|
||||
net::{BINCODE_CONFIG, ClientMsg, SERVER_NAME, no_cert::SkipServerVerification},
|
||||
};
|
||||
use quinn::{ClientConfig, Connection, Endpoint, crypto::rustls::QuicClientConfig};
|
||||
use std::{
|
||||
net::{Ipv6Addr, SocketAddr, SocketAddrV6, ToSocketAddrs},
|
||||
str::FromStr,
|
||||
sync::Arc,
|
||||
};
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
use tokio::{io::AsyncWriteExt, sync::mpsc::UnboundedSender};
|
||||
|
||||
pub const CLIENT_SOCKET: SocketAddr =
|
||||
SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0));
|
||||
@@ -19,11 +18,7 @@ pub fn connect(handle: AppHandle, ip: String) {
|
||||
});
|
||||
}
|
||||
|
||||
pub enum NetCmd {
|
||||
SendMsg(String),
|
||||
}
|
||||
|
||||
pub type NetSender = UnboundedSender<NetCmd>;
|
||||
pub type NetSender = UnboundedSender<ClientMsg>;
|
||||
|
||||
// async fn connection_cert(addr: SocketAddr) -> anyhow::Result<Connection> {
|
||||
// let dirs = directories_next::ProjectDirs::from("", "", "openworm").unwrap();
|
||||
@@ -71,30 +66,27 @@ async fn connection_no_cert(addr: SocketAddr) -> anyhow::Result<Connection> {
|
||||
|
||||
#[tokio::main]
|
||||
async fn connect_the(handle: AppHandle, ip: String) -> anyhow::Result<()> {
|
||||
let (client_send, mut client_recv) = tokio::sync::mpsc::unbounded_channel::<NetCmd>();
|
||||
let (client_send, mut client_recv) = tokio::sync::mpsc::unbounded_channel::<ClientMsg>();
|
||||
|
||||
handle.send(ClientEvent::Connect(client_send));
|
||||
let addr = ip.to_socket_addrs().unwrap().next().unwrap();
|
||||
// let addr = SocketAddr::from_str(&ip).unwrap();
|
||||
let conn = connection_no_cert(addr).await?;
|
||||
|
||||
while let Some(msg) = client_recv.recv().await {
|
||||
match msg {
|
||||
NetCmd::SendMsg(content) => {
|
||||
let (mut send, recv) = conn
|
||||
.open_bi()
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("failed to open stream: {e}"))?;
|
||||
let bytes = bincode::encode_to_vec(msg, BINCODE_CONFIG).unwrap();
|
||||
let (mut send, recv) = conn
|
||||
.open_bi()
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("failed to open stream: {e}"))?;
|
||||
|
||||
drop(recv);
|
||||
drop(recv);
|
||||
|
||||
send.write_all(content.as_bytes())
|
||||
.await
|
||||
.expect("failed to send");
|
||||
send.finish().unwrap();
|
||||
send.stopped().await.unwrap();
|
||||
}
|
||||
}
|
||||
send.write_u64(bytes.len() as u64)
|
||||
.await
|
||||
.expect("failed to send");
|
||||
send.write_all(&bytes).await.expect("failed to send");
|
||||
send.finish().unwrap();
|
||||
send.stopped().await.unwrap();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
use bincode::config::Configuration;
|
||||
|
||||
pub mod client;
|
||||
mod no_cert;
|
||||
pub mod server;
|
||||
|
||||
pub const SERVER_NAME: &str = "openworm";
|
||||
pub const BINCODE_CONFIG: Configuration = bincode::config::standard();
|
||||
|
||||
#[derive(Debug, bincode::Encode, bincode::Decode)]
|
||||
pub enum ClientMsg {
|
||||
SendMsg { content: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, bincode::Encode, bincode::Decode)]
|
||||
pub enum ServerMsg {
|
||||
RecvMsg { content: String },
|
||||
}
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
use crate::net::SERVER_NAME;
|
||||
use crate::net::{BINCODE_CONFIG, ClientMsg, SERVER_NAME};
|
||||
use quinn::{
|
||||
Endpoint, ServerConfig,
|
||||
rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer},
|
||||
};
|
||||
use std::net::{Ipv6Addr, SocketAddr, SocketAddrV6};
|
||||
use std::{fs, path::Path};
|
||||
use std::{
|
||||
net::{Ipv6Addr, SocketAddr, SocketAddrV6},
|
||||
sync::Arc,
|
||||
};
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tracing::Instrument;
|
||||
|
||||
pub const DEFAULT_PORT: u16 = 16839;
|
||||
pub const SERVER_HOST: Ipv6Addr = Ipv6Addr::UNSPECIFIED;
|
||||
pub const SERVER_SOCKET: SocketAddr =
|
||||
SocketAddr::V6(SocketAddrV6::new(SERVER_HOST, DEFAULT_PORT, 0, 0));
|
||||
|
||||
pub fn listen(data_path: &Path) -> Endpoint {
|
||||
pub fn init_endpoint(data_path: &Path) -> Endpoint {
|
||||
let cert_path = data_path.join("cert.der");
|
||||
let key_path = data_path.join("key.der");
|
||||
let (cert, key) = match fs::read(&cert_path).and_then(|x| Ok((x, fs::read(&key_path)?))) {
|
||||
@@ -47,3 +52,83 @@ pub fn listen(data_path: &Path) -> Endpoint {
|
||||
|
||||
quinn::Endpoint::server(server_config, SERVER_SOCKET).unwrap()
|
||||
}
|
||||
|
||||
pub trait ConHandler: Send + Sync + 'static {
|
||||
fn on_msg(&self, msg: ClientMsg);
|
||||
}
|
||||
|
||||
pub async fn listen(data_path: &Path, handler: impl ConHandler) {
|
||||
let handler = Arc::new(handler);
|
||||
let endpoint = init_endpoint(data_path);
|
||||
println!("listening on {}", endpoint.local_addr().unwrap());
|
||||
|
||||
while let Some(conn) = endpoint.accept().await {
|
||||
let fut = handle_connection(conn, handler.clone());
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = fut.await {
|
||||
eprintln!("connection failed: {reason}", reason = e)
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_connection(
|
||||
conn: quinn::Incoming,
|
||||
handler: Arc<impl ConHandler>,
|
||||
) -> std::io::Result<()> {
|
||||
let connection = conn.await?;
|
||||
let span = tracing::info_span!(
|
||||
"connection",
|
||||
remote = %connection.remote_address(),
|
||||
protocol = %connection
|
||||
.handshake_data()
|
||||
.unwrap()
|
||||
.downcast::<quinn::crypto::rustls::HandshakeData>().unwrap()
|
||||
.protocol
|
||||
.map_or_else(|| "<none>".into(), |x| String::from_utf8_lossy(&x).into_owned())
|
||||
);
|
||||
async {
|
||||
// Each stream initiated by the client constitutes a new request.
|
||||
loop {
|
||||
let stream = connection.accept_bi().await;
|
||||
// let time = Instant::now();
|
||||
let stream = match stream {
|
||||
Err(quinn::ConnectionError::ApplicationClosed { .. }) => {
|
||||
println!("connection closed");
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(e);
|
||||
}
|
||||
Ok(s) => s,
|
||||
};
|
||||
let handler = handler.clone();
|
||||
tokio::spawn(
|
||||
async move {
|
||||
if let Err(e) = handle_stream(stream, handler).await {
|
||||
eprintln!("failed: {reason}", reason = e);
|
||||
}
|
||||
}
|
||||
.instrument(tracing::info_span!("request")),
|
||||
);
|
||||
}
|
||||
}
|
||||
.instrument(span)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_stream(
|
||||
(send, mut recv): (quinn::SendStream, quinn::RecvStream),
|
||||
handler: Arc<impl ConHandler>,
|
||||
) -> Result<(), String> {
|
||||
drop(send);
|
||||
let len = recv.read_u64().await.unwrap();
|
||||
let bytes = recv
|
||||
.read_to_end(len as usize)
|
||||
.await
|
||||
.map_err(|e| format!("failed reading request: {}", e))?;
|
||||
let (msg, _) = bincode::decode_from_slice::<ClientMsg, _>(&bytes, BINCODE_CONFIG).unwrap();
|
||||
handler.on_msg(msg);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,74 +1,20 @@
|
||||
use crate::net::{ClientMsg, server::listen};
|
||||
use tracing::Instrument;
|
||||
use crate::net::{
|
||||
ClientMsg,
|
||||
server::{ConHandler, listen},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
pub async fn run_server() {
|
||||
let dirs = directories_next::ProjectDirs::from("", "", "openworm").unwrap();
|
||||
let path = dirs.data_local_dir();
|
||||
let endpoint = listen(path);
|
||||
println!("listening on {}", endpoint.local_addr().unwrap());
|
||||
let handler = ClientHandler {};
|
||||
listen(path, handler).await;
|
||||
}
|
||||
|
||||
while let Some(conn) = endpoint.accept().await {
|
||||
let fut = handle_connection(conn);
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = fut.await {
|
||||
eprintln!("connection failed: {reason}", reason = e)
|
||||
}
|
||||
});
|
||||
pub struct ClientHandler {}
|
||||
|
||||
impl ConHandler for ClientHandler {
|
||||
fn on_msg(&self, msg: ClientMsg) {
|
||||
println!("received msg: {msg:?}");
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_connection(conn: quinn::Incoming) -> std::io::Result<()> {
|
||||
let connection = conn.await?;
|
||||
let span = tracing::info_span!(
|
||||
"connection",
|
||||
remote = %connection.remote_address(),
|
||||
protocol = %connection
|
||||
.handshake_data()
|
||||
.unwrap()
|
||||
.downcast::<quinn::crypto::rustls::HandshakeData>().unwrap()
|
||||
.protocol
|
||||
.map_or_else(|| "<none>".into(), |x| String::from_utf8_lossy(&x).into_owned())
|
||||
);
|
||||
async {
|
||||
// Each stream initiated by the client constitutes a new request.
|
||||
loop {
|
||||
let stream = connection.accept_bi().await;
|
||||
// let time = Instant::now();
|
||||
let stream = match stream {
|
||||
Err(quinn::ConnectionError::ApplicationClosed { .. }) => {
|
||||
println!("connection closed");
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(e);
|
||||
}
|
||||
Ok(s) => s,
|
||||
};
|
||||
tokio::spawn(
|
||||
async move {
|
||||
if let Err(e) = handle_stream(stream).await {
|
||||
eprintln!("failed: {reason}", reason = e);
|
||||
}
|
||||
}
|
||||
.instrument(tracing::info_span!("request")),
|
||||
);
|
||||
}
|
||||
}
|
||||
.instrument(span)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_stream(
|
||||
(send, mut recv): (quinn::SendStream, quinn::RecvStream),
|
||||
) -> Result<(), String> {
|
||||
drop(send);
|
||||
let bytes = recv
|
||||
.read_to_end(std::mem::size_of::<ClientMsg>())
|
||||
.await
|
||||
.map_err(|e| format!("failed reading request: {}", e))?;
|
||||
let msg = String::from_utf8(bytes).unwrap();
|
||||
println!("received message: {:?}", msg);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user