WORKING BASIC MSG SERVER

This commit is contained in:
2025-11-17 01:44:22 -05:00
parent 8a9e766633
commit 46a566ebd0
8 changed files with 265 additions and 115 deletions

View File

@@ -62,7 +62,7 @@ impl ApplicationHandler<ClientEvent> for App {
impl AppHandle { impl AppHandle {
pub fn send(&self, event: ClientEvent) { pub fn send(&self, event: ClientEvent) {
self.proxy.send_event(event).unwrap(); self.proxy.send_event(event).unwrap_or_else(|_| panic!());
self.window.request_redraw(); self.window.request_redraw();
} }
} }

View File

@@ -6,8 +6,8 @@ use render::Renderer;
use winit::{event::WindowEvent, event_loop::ActiveEventLoop}; use winit::{event::WindowEvent, event_loop::ActiveEventLoop};
use crate::{ use crate::{
client::ui::{Submit, main_view}, client::ui::{Submit, main_view, msg_widget},
net::client::NetSender, net::{ClientMsg, ServerMsg, client::NetSender},
}; };
mod app; mod app;
@@ -17,9 +17,9 @@ mod ui;
pub use app::AppHandle; pub use app::AppHandle;
#[derive(Debug)]
pub enum ClientEvent { pub enum ClientEvent {
Connect(NetSender), Connect { send: NetSender, username: String },
ServerMsg(ServerMsg),
} }
pub struct Client { pub struct Client {
@@ -27,6 +27,8 @@ pub struct Client {
input: Input, input: Input,
ui: Ui, ui: Ui,
focus: Option<WidgetId<TextEdit>>, focus: Option<WidgetId<TextEdit>>,
channel: Option<WidgetId<Span>>,
username: String,
clipboard: Clipboard, clipboard: Clipboard,
} }
@@ -40,16 +42,36 @@ impl Client {
renderer, renderer,
input: Input::default(), input: Input::default(),
ui, ui,
channel: None,
focus: None, focus: None,
username: "<unknown>".to_string(),
clipboard: Clipboard::new().unwrap(), clipboard: Clipboard::new().unwrap(),
} }
} }
pub fn event(&mut self, event: ClientEvent, _: &ActiveEventLoop) { pub fn event(&mut self, event: ClientEvent, _: &ActiveEventLoop) {
match event { match event {
ClientEvent::Connect(send) => { ClientEvent::Connect { send, username } => {
main_view(&mut self.ui, send).set_root(&mut self.ui); self.username = username;
send.send(ClientMsg::RequestMsgs);
main_view(self, send).set_root(&mut self.ui);
} }
ClientEvent::ServerMsg(msg) => match msg {
ServerMsg::SendMsg(msg) => {
if let Some(msg_area) = &self.channel {
let msg = msg_widget(msg).add(&mut self.ui);
self.ui[msg_area].children.push(msg.any());
}
}
ServerMsg::LoadMsgs(msgs) => {
if let Some(msg_area) = &self.channel {
for msg in msgs {
let msg = msg_widget(msg).add(&mut self.ui);
self.ui[msg_area].children.push(msg.any());
}
}
}
},
} }
} }

View File

@@ -4,8 +4,8 @@ use len_fns::*;
use crate::{ use crate::{
client::{Client, app::AppHandle}, client::{Client, app::AppHandle},
net::{ net::{
ClientMsg, ClientMsg, Msg,
client::{NetSender, connect}, client::{ConnectInfo, NetSender, connect},
}, },
}; };
@@ -22,17 +22,20 @@ pub fn ui(handle: AppHandle) -> Ui {
ui ui
} }
pub fn main_view(ui: &mut Ui, network: NetSender) -> WidgetId<AnyWidget> { pub fn main_view(client: &mut Client, network: NetSender) -> WidgetId<AnyWidget> {
let msg_panel = msg_panel(ui, network); let msg_panel = msg_panel(client, network);
let side_bar = rect(Color::BLACK.brighter(0.05)).width(80); let side_bar = rect(Color::BLACK.brighter(0.05)).width(80);
(side_bar, msg_panel).span(Dir::RIGHT).add(ui).any() (side_bar, msg_panel)
.span(Dir::RIGHT)
.add(&mut client.ui)
.any()
} }
fn login_screen(ui: &mut Ui, handle: AppHandle) -> WidgetId<AnyWidget> { fn login_screen(ui: &mut Ui, handle: AppHandle) -> WidgetId<AnyWidget> {
let mut field = |name| text(name).editable().size(20).add(ui); let mut field = |name| text(name).editable().size(20).add(ui);
let ip = field("ip"); let ip = field("localhost:16839");
// let username = field("username"); let username = field("username");
// let password = field("password"); // let password = field("password");
let fbx = |field: WidgetId<TextEdit>| { let fbx = |field: WidgetId<TextEdit>| {
@@ -44,19 +47,21 @@ fn login_screen(ui: &mut Ui, handle: AppHandle) -> WidgetId<AnyWidget> {
}; };
let ip_ = ip.clone(); let ip_ = ip.clone();
let username_ = username.clone();
let color = Color::GREEN; let color = Color::GREEN;
let submit = rect(color) let submit = rect(color)
.radius(15) .radius(15)
.id_on(CursorSense::click(), move |id, client: &mut Client, _| { .id_on(CursorSense::click(), move |id, client: &mut Client, _| {
client.ui[id].color = color.darker(0.3); client.ui[id].color = color.darker(0.3);
let ip = client.ui[&ip_].content(); let ip = client.ui[&ip_].content();
connect(handle.clone(), ip); let username = client.ui[&username_].content();
connect(handle.clone(), ConnectInfo { ip, username });
}) })
.height(40); .height(40);
( (
text("login").size(30), text("login").size(30),
fbx(ip), fbx(ip),
// fbx(username), fbx(username),
// fbx(password), // fbx(password),
submit, submit,
) )
@@ -70,8 +75,8 @@ fn login_screen(ui: &mut Ui, handle: AppHandle) -> WidgetId<AnyWidget> {
.any() .any()
} }
fn msg_widget(content: String) -> impl WidgetLike<FnTag> { pub fn msg_widget(msg: Msg) -> impl WidgetLike<FnTag> {
let content = text(content) let content = text(msg.content)
.editable() .editable()
.size(20) .size(20)
.text_align(Align::Left) .text_align(Align::Left)
@@ -80,7 +85,7 @@ fn msg_widget(content: String) -> impl WidgetLike<FnTag> {
client.ui.text(id).select(ctx.cursor, ctx.size); client.ui.text(id).select(ctx.cursor, ctx.size);
client.focus = Some(id.clone()); client.focus = Some(id.clone());
}); });
let header = text("some user").size(20); let header = text(msg.user).size(20);
( (
image(include_bytes!("./assets/sungals.png")) image(include_bytes!("./assets/sungals.png"))
.sized((70, 70)) .sized((70, 70))
@@ -100,14 +105,12 @@ pub fn focus(id: WidgetId<TextEdit>) -> impl Fn(&mut Client, CursorData) {
} }
} }
pub fn msg_panel(ui: &mut Ui, network: NetSender) -> impl WidgetFn<Stack> + use<> { pub fn msg_panel(client: &mut Client, network: NetSender) -> impl WidgetFn<Stack> + use<> {
let Client { ui, channel, .. } = client;
let msg_area = Span::empty(Dir::DOWN).gap(15).add(ui); let msg_area = Span::empty(Dir::DOWN).gap(15).add(ui);
*channel = Some(msg_area.clone());
let send_text = text("some stuff idk") let send_text = text("").editable().size(20).text_align(Align::Left).add(ui);
.editable()
.size(20)
.text_align(Align::Left)
.add(ui);
( (
msg_area msg_area
@@ -120,12 +123,12 @@ pub fn msg_panel(ui: &mut Ui, network: NetSender) -> impl WidgetFn<Stack> + use<
.clone() .clone()
.id_on(Submit, move |id, client: &mut Client, _| { .id_on(Submit, move |id, client: &mut Client, _| {
let content = client.ui.text(id).take(); let content = client.ui.text(id).take();
network let msg = Msg {
.send(ClientMsg::SendMsg { content: content.clone(),
content: content.clone(), user: client.username.clone(),
}) };
.unwrap(); network.send(ClientMsg::SendMsg(msg.clone()));
let msg = msg_widget(content).add(&mut client.ui); let msg = msg_widget(msg).add(&mut client.ui);
client.ui[&msg_area].children.push(msg.any()); client.ui[&msg_area].children.push(msg.any());
}) })
.pad(15) .pad(15)

View File

@@ -1,24 +1,42 @@
use crate::{ use crate::{
client::{AppHandle, ClientEvent}, client::{AppHandle, ClientEvent},
net::{BINCODE_CONFIG, ClientMsg, SERVER_NAME, no_cert::SkipServerVerification}, net::{
ClientMsg, SERVER_NAME, ServerMsg,
no_cert::SkipServerVerification,
transfer::{RecvHandler, recv_uni, send_uni},
},
}; };
use quinn::{ClientConfig, Connection, Endpoint, crypto::rustls::QuicClientConfig}; use quinn::{ClientConfig, Connection, Endpoint, crypto::rustls::QuicClientConfig};
use std::{ use std::{
net::{Ipv6Addr, SocketAddr, SocketAddrV6, ToSocketAddrs}, net::{Ipv6Addr, SocketAddr, SocketAddrV6, ToSocketAddrs},
sync::Arc, sync::Arc,
}; };
use tokio::{io::AsyncWriteExt, sync::mpsc::UnboundedSender}; use tokio::sync::mpsc::UnboundedSender;
pub const CLIENT_SOCKET: SocketAddr = pub const CLIENT_SOCKET: SocketAddr =
SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0)); SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0));
pub fn connect(handle: AppHandle, ip: String) { pub struct ConnectInfo {
pub ip: String,
pub username: String,
}
pub fn connect(handle: AppHandle, info: ConnectInfo) {
std::thread::spawn(|| { std::thread::spawn(|| {
connect_the(handle, ip).unwrap(); connect_the(handle, info).unwrap();
}); });
} }
pub type NetSender = UnboundedSender<ClientMsg>; type MsgPayload = ClientMsg;
pub struct NetSender {
send: UnboundedSender<MsgPayload>,
}
impl NetSender {
pub fn send(&self, msg: ClientMsg) {
self.send.send(msg).unwrap();
}
}
// async fn connection_cert(addr: SocketAddr) -> anyhow::Result<Connection> { // async fn connection_cert(addr: SocketAddr) -> anyhow::Result<Connection> {
// let dirs = directories_next::ProjectDirs::from("", "", "openworm").unwrap(); // let dirs = directories_next::ProjectDirs::from("", "", "openworm").unwrap();
@@ -65,29 +83,36 @@ async fn connection_no_cert(addr: SocketAddr) -> anyhow::Result<Connection> {
} }
#[tokio::main] #[tokio::main]
async fn connect_the(handle: AppHandle, ip: String) -> anyhow::Result<()> { async fn connect_the(handle: AppHandle, info: ConnectInfo) -> anyhow::Result<()> {
let (client_send, mut client_recv) = tokio::sync::mpsc::unbounded_channel::<ClientMsg>(); let (send, mut ui_recv) = tokio::sync::mpsc::unbounded_channel::<MsgPayload>();
handle.send(ClientEvent::Connect(client_send)); handle.send(ClientEvent::Connect {
let addr = ip.to_socket_addrs().unwrap().next().unwrap(); username: info.username,
send: NetSender { send },
});
let addr = info.ip.to_socket_addrs().unwrap().next().unwrap();
let conn = connection_no_cert(addr).await?; let conn = connection_no_cert(addr).await?;
let conn_ = conn.clone();
while let Some(msg) = client_recv.recv().await { let recv = ServerRecv { handle };
let bytes = bincode::encode_to_vec(msg, BINCODE_CONFIG).unwrap(); tokio::spawn(recv_uni(conn_, recv));
let (mut send, recv) = conn
.open_bi()
.await
.map_err(|e| anyhow::anyhow!("failed to open stream: {e}"))?;
drop(recv); while let Some(msg) = ui_recv.recv().await {
if send_uni(&conn, msg).await.is_err() {
send.write_u64(bytes.len() as u64) println!("disconnected from server");
.await break;
.expect("failed to send"); }
send.write_all(&bytes).await.expect("failed to send");
send.finish().unwrap();
send.stopped().await.unwrap();
} }
Ok(()) Ok(())
} }
struct ServerRecv {
handle: AppHandle,
}
impl RecvHandler<ServerMsg> for ServerRecv {
async fn msg(&self, msg: ServerMsg) {
self.handle.send(ClientEvent::ServerMsg(msg));
}
}

View File

@@ -3,16 +3,27 @@ use bincode::config::Configuration;
pub mod client; pub mod client;
mod no_cert; mod no_cert;
pub mod server; pub mod server;
pub mod transfer;
pub const SERVER_NAME: &str = "openworm"; pub const SERVER_NAME: &str = "openworm";
pub const BINCODE_CONFIG: Configuration = bincode::config::standard(); pub const BINCODE_CONFIG: Configuration = bincode::config::standard();
#[derive(Debug, bincode::Encode, bincode::Decode)] #[derive(Debug, bincode::Encode, bincode::Decode)]
pub enum ClientMsg { pub enum ClientMsg {
SendMsg { content: String }, SendMsg(Msg),
RequestMsgs,
} }
#[derive(Debug, bincode::Encode, bincode::Decode)] #[derive(Debug, bincode::Encode, bincode::Decode)]
pub enum ServerMsg { pub enum ServerMsg {
RecvMsg { content: String }, SendMsg(Msg),
LoadMsgs(Vec<Msg>),
}
pub type ServerResp<T> = Result<T, String>;
#[derive(Debug, Clone, bincode::Encode, bincode::Decode)]
pub struct Msg {
pub content: String,
pub user: String,
} }

View File

@@ -1,6 +1,9 @@
use crate::net::{BINCODE_CONFIG, ClientMsg, SERVER_NAME}; use crate::net::{
ClientMsg, SERVER_NAME, ServerMsg,
transfer::{RecvHandler, SendResult, recv_uni, send_uni},
};
use quinn::{ use quinn::{
Endpoint, ServerConfig, Connection, Endpoint, ServerConfig,
rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer}, rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer},
}; };
use std::{fs, path::Path}; use std::{fs, path::Path};
@@ -8,7 +11,6 @@ use std::{
net::{Ipv6Addr, SocketAddr, SocketAddrV6}, net::{Ipv6Addr, SocketAddr, SocketAddrV6},
sync::Arc, sync::Arc,
}; };
use tokio::io::AsyncReadExt;
use tracing::Instrument; use tracing::Instrument;
pub const DEFAULT_PORT: u16 = 16839; pub const DEFAULT_PORT: u16 = 16839;
@@ -53,17 +55,31 @@ pub fn init_endpoint(data_path: &Path) -> Endpoint {
quinn::Endpoint::server(server_config, SERVER_SOCKET).unwrap() quinn::Endpoint::server(server_config, SERVER_SOCKET).unwrap()
} }
pub trait ConHandler: Send + Sync + 'static { #[derive(Clone)]
fn on_msg(&self, msg: ClientMsg); pub struct ClientSender {
conn: Connection,
} }
pub async fn listen(data_path: &Path, handler: impl ConHandler) { impl ClientSender {
let handler = Arc::new(handler); pub async fn send(&self, msg: ServerMsg) -> SendResult {
send_uni(&self.conn, msg).await
}
}
pub trait ConAccepter: Send + Sync + 'static {
fn accept(
&self,
send: ClientSender,
) -> impl Future<Output = impl RecvHandler<ClientMsg>> + Send;
}
pub async fn listen(data_path: &Path, accepter: impl ConAccepter) {
let accepter = Arc::new(accepter);
let endpoint = init_endpoint(data_path); let endpoint = init_endpoint(data_path);
println!("listening on {}", endpoint.local_addr().unwrap()); println!("listening on {}", endpoint.local_addr().unwrap());
while let Some(conn) = endpoint.accept().await { while let Some(conn) = endpoint.accept().await {
let fut = handle_connection(conn, handler.clone()); let fut = handle_connection(conn, accepter.clone());
tokio::spawn(async move { tokio::spawn(async move {
if let Err(e) = fut.await { if let Err(e) = fut.await {
eprintln!("connection failed: {reason}", reason = e) eprintln!("connection failed: {reason}", reason = e)
@@ -74,13 +90,14 @@ pub async fn listen(data_path: &Path, handler: impl ConHandler) {
async fn handle_connection( async fn handle_connection(
conn: quinn::Incoming, conn: quinn::Incoming,
handler: Arc<impl ConHandler>, accepter: Arc<impl ConAccepter>,
) -> std::io::Result<()> { ) -> std::io::Result<()> {
let connection = conn.await?; let conn = conn.await?;
let handler = accepter.accept(ClientSender { conn: conn.clone() }).await;
let span = tracing::info_span!( let span = tracing::info_span!(
"connection", "connection",
remote = %connection.remote_address(), remote = %conn.remote_address(),
protocol = %connection protocol = %conn
.handshake_data() .handshake_data()
.unwrap() .unwrap()
.downcast::<quinn::crypto::rustls::HandshakeData>().unwrap() .downcast::<quinn::crypto::rustls::HandshakeData>().unwrap()
@@ -88,47 +105,9 @@ async fn handle_connection(
.map_or_else(|| "<none>".into(), |x| String::from_utf8_lossy(&x).into_owned()) .map_or_else(|| "<none>".into(), |x| String::from_utf8_lossy(&x).into_owned())
); );
async { async {
// Each stream initiated by the client constitutes a new request. recv_uni(conn, handler).await;
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) .instrument(span)
.await?; .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(()) Ok(())
} }

48
src/net/transfer.rs Normal file
View File

@@ -0,0 +1,48 @@
use std::sync::Arc;
use crate::net::BINCODE_CONFIG;
use quinn::Connection;
use tokio::io::{AsyncReadExt as _, AsyncWriteExt};
use tracing::Instrument as _;
pub trait RecvHandler<M>: Send + Sync + 'static {
fn msg(&self, msg: M) -> impl Future<Output = ()> + Send;
}
pub type SendResult = Result<(), ()>;
pub async fn send_uni<M: bincode::Encode>(conn: &Connection, msg: M) -> SendResult {
let bytes = bincode::encode_to_vec(msg, BINCODE_CONFIG).unwrap();
let mut send = conn.open_uni().await.map_err(|_| ())?;
send.write_u64(bytes.len() as u64).await.map_err(|_| ())?;
send.write_all(&bytes).await.map_err(|_| ())?;
send.finish().map_err(|_| ())?;
send.stopped().await.map_err(|_| ())?;
Ok(())
}
pub async fn recv_uni<M: bincode::Decode<()>>(conn: Connection, handler: impl RecvHandler<M>) {
let handler = Arc::new(handler);
loop {
let mut recv = match conn.accept_uni().await {
Err(quinn::ConnectionError::ApplicationClosed { .. }) => {
return;
}
Err(e) => {
eprintln!("connection error: {e}");
return;
}
Ok(s) => s,
};
let handler = handler.clone();
tokio::spawn(
async move {
let len = recv.read_u64().await.unwrap();
let bytes = recv.read_to_end(len as usize).await.unwrap();
let (msg, _) = bincode::decode_from_slice::<M, _>(&bytes, BINCODE_CONFIG).unwrap();
handler.msg(msg).await;
}
.instrument(tracing::info_span!("request")),
);
}
}

View File

@@ -1,20 +1,82 @@
use crate::net::{ use crate::net::{
ClientMsg, ClientMsg, Msg, ServerMsg,
server::{ConHandler, listen}, server::{ClientSender, ConAccepter, listen},
transfer::RecvHandler,
}; };
use std::{
collections::HashMap,
sync::{
Arc,
atomic::{AtomicU64, Ordering},
},
};
use tokio::sync::RwLock;
#[tokio::main] #[tokio::main]
pub async fn run_server() { pub async fn run_server() {
let dirs = directories_next::ProjectDirs::from("", "", "openworm").unwrap(); let dirs = directories_next::ProjectDirs::from("", "", "openworm").unwrap();
let path = dirs.data_local_dir(); let path = dirs.data_local_dir();
let handler = ClientHandler {}; let handler = ServerListener {
msgs: Default::default(),
senders: Default::default(),
count: 0.into(),
};
listen(path, handler).await; listen(path, handler).await;
} }
pub struct ClientHandler {} type ClientId = u64;
impl ConHandler for ClientHandler { struct ServerListener {
fn on_msg(&self, msg: ClientMsg) { msgs: Arc<RwLock<Vec<Msg>>>,
println!("received msg: {msg:?}"); senders: Arc<RwLock<HashMap<ClientId, ClientSender>>>,
count: AtomicU64,
}
impl ConAccepter for ServerListener {
async fn accept(&self, send: ClientSender) -> impl RecvHandler<ClientMsg> {
let id = self.count.fetch_add(1, Ordering::Release);
self.senders.write().await.insert(id, send.clone());
ClientHandler {
msgs: self.msgs.clone(),
senders: self.senders.clone(),
send,
id,
}
}
}
struct ClientHandler {
msgs: Arc<RwLock<Vec<Msg>>>,
send: ClientSender,
senders: Arc<RwLock<HashMap<ClientId, ClientSender>>>,
id: ClientId,
}
impl RecvHandler<ClientMsg> for ClientHandler {
async fn msg(&self, msg: ClientMsg) {
match msg {
ClientMsg::SendMsg(msg) => {
self.msgs.write().await.push(msg.clone());
let mut handles = Vec::new();
for (&id, send) in self.senders.read().await.iter() {
if id == self.id {
continue;
}
let send = send.clone();
let msg = msg.clone();
let fut = async move {
let _ = send.send(ServerMsg::SendMsg(msg)).await;
};
handles.push(tokio::spawn(fut));
}
for h in handles {
h.await.unwrap();
}
}
ClientMsg::RequestMsgs => {
let msgs = self.msgs.read().await.clone();
let _ = self.send.send(ServerMsg::LoadMsgs(msgs)).await;
}
}
} }
} }