pub struct Server { /* private fields */ }Expand description
Server is the thread-safe handle to a running NWEP server.
Server is obtained from ServerBuilder::build alongside an EventLoop. It can be
cloned and sent across threads freely; all mutating operations are communicated to the event
loop via an internal channel.
Implementations§
Source§impl Server
impl Server
Sourcepub fn addr(&self) -> SocketAddr
pub fn addr(&self) -> SocketAddr
addr returns the local UDP socket address the server is listening on.
Examples found in repository?
35fn main() {
36 nwep::init().unwrap_or_else(|e| {
37 eprintln!("init: {e}");
38 process::exit(1);
39 });
40
41 let key_file = std::env::var("NWEP_KEY_FILE").unwrap_or_else(|_| DEFAULT_KEY_FILE.into());
42 let keypair = load_or_generate_keypair(&key_file).unwrap_or_else(|e| {
43 eprintln!("keypair: {e}");
44 process::exit(1);
45 });
46
47 let node_id = keypair.node_id().unwrap_or_else(|e| {
48 eprintln!("node_id: {e}");
49 process::exit(1);
50 });
51 eprintln!("node id: {node_id}");
52
53 let mut router = Router::new();
54 router.handle_func("/hello", |w: &mut ResponseWriter, _r: &Request| {
55 let _ = w.respond("ok", b"hello from nwep-rust");
56 });
57
58 let addr = std::env::args().nth(1).unwrap_or_else(|| DEFAULT_ADDR.into());
59
60 let (server, event_loop) = ServerBuilder::new(&addr, keypair)
61 .on_connect(|info| eprintln!("connected: {}", info.node_id))
62 .on_disconnect(|info, code| eprintln!("disconnected: {} (code {code})", info.node_id))
63 .build(router)
64 .unwrap_or_else(|e| {
65 eprintln!("server: {e}");
66 process::exit(1);
67 });
68
69 let url = server.url("/hello");
70 eprintln!("listening on {}", server.addr());
71 println!("{url}"); // URL printed to stdout for the client to read
72
73 if let Err(e) = event_loop.run() {
74 eprintln!("server run: {e}");
75 process::exit(1);
76 }
77}Sourcepub fn url(&self, path: &str) -> String
pub fn url(&self, path: &str) -> String
url formats a web:// URL for the given path on this server.
If the server was bound to an unspecified address (0.0.0.0 or ::), the URL uses
the loopback address instead, matching Go’s server.URL() behaviour.
§Example
println!("{}", server.url("/hello")); // e.g. "web://127.0.0.1:<node_id>:8080/hello"Examples found in repository?
35fn main() {
36 nwep::init().unwrap_or_else(|e| {
37 eprintln!("init: {e}");
38 process::exit(1);
39 });
40
41 let key_file = std::env::var("NWEP_KEY_FILE").unwrap_or_else(|_| DEFAULT_KEY_FILE.into());
42 let keypair = load_or_generate_keypair(&key_file).unwrap_or_else(|e| {
43 eprintln!("keypair: {e}");
44 process::exit(1);
45 });
46
47 let node_id = keypair.node_id().unwrap_or_else(|e| {
48 eprintln!("node_id: {e}");
49 process::exit(1);
50 });
51 eprintln!("node id: {node_id}");
52
53 let mut router = Router::new();
54 router.handle_func("/hello", |w: &mut ResponseWriter, _r: &Request| {
55 let _ = w.respond("ok", b"hello from nwep-rust");
56 });
57
58 let addr = std::env::args().nth(1).unwrap_or_else(|| DEFAULT_ADDR.into());
59
60 let (server, event_loop) = ServerBuilder::new(&addr, keypair)
61 .on_connect(|info| eprintln!("connected: {}", info.node_id))
62 .on_disconnect(|info, code| eprintln!("disconnected: {} (code {code})", info.node_id))
63 .build(router)
64 .unwrap_or_else(|e| {
65 eprintln!("server: {e}");
66 process::exit(1);
67 });
68
69 let url = server.url("/hello");
70 eprintln!("listening on {}", server.addr());
71 println!("{url}"); // URL printed to stdout for the client to read
72
73 if let Err(e) = event_loop.run() {
74 eprintln!("server run: {e}");
75 process::exit(1);
76 }
77}Sourcepub fn connection_count(&self) -> usize
pub fn connection_count(&self) -> usize
connection_count returns the number of currently authenticated, connected peers.
The count is updated synchronously on the event loop thread when a peer connects or disconnects, so it may lag slightly behind the network state.
Sourcepub fn connected_peers(&self) -> Vec<NodeId>
pub fn connected_peers(&self) -> Vec<NodeId>
connected_peers returns a snapshot of the node IDs of all currently connected peers.
Sourcepub fn shutdown(&self)
pub fn shutdown(&self)
shutdown signals the event loop to stop accepting new connections and exit.
This call returns immediately; wait for EventLoop::run to return to confirm the
server has fully stopped.
Sourcepub fn notify(
&self,
peer_node_id: NodeId,
event: &str,
path: &str,
body: Vec<u8>,
) -> Result<(), Error>
pub fn notify( &self, peer_node_id: NodeId, event: &str, path: &str, body: Vec<u8>, ) -> Result<(), Error>
notify sends a server-initiated push message to a single connected peer.
The peer receives the notification in its on_notify callback. event is a
free-form event type string; path is the resource path; body is the payload.
§Errors
Returns an error if the internal channel has been closed (i.e. the event loop has already stopped).
Sourcepub fn notify_with_options(
&self,
peer_node_id: NodeId,
event: &str,
path: &str,
body: Vec<u8>,
options: NotifyOptions,
) -> Result<(), Error>
pub fn notify_with_options( &self, peer_node_id: NodeId, event: &str, path: &str, body: Vec<u8>, options: NotifyOptions, ) -> Result<(), Error>
notify_with_options sends a server-initiated push message with additional metadata.
Like notify but also accepts a NotifyOptions to attach custom
headers or a stable notification identifier to the wire message.
§Errors
Returns an error if the internal channel has been closed.
Sourcepub fn notify_all(
&self,
event: &str,
path: &str,
body: Vec<u8>,
) -> Result<(), Error>
pub fn notify_all( &self, event: &str, path: &str, body: Vec<u8>, ) -> Result<(), Error>
notify_all broadcasts a push notification to every currently connected peer.
The message is sent to the snapshot of connections held by the event loop at the time it processes the event; peers that disconnect between the call and processing are silently skipped.
§Errors
Returns an error if the internal channel has been closed.
Sourcepub fn close_connection(
&self,
peer_node_id: NodeId,
error: i32,
) -> Result<(), Error>
pub fn close_connection( &self, peer_node_id: NodeId, error: i32, ) -> Result<(), Error>
close_connection forcefully closes the connection to the identified peer.
The peer is removed from internal state immediately and the on_disconnect callback
fires before the QUIC CONNECTION_CLOSE is sent. This is intentional: the C
library’s QUIC CLOSING state is asynchronous and the disconnect callback would
otherwise be delayed until the peer sends a packet.
§Errors
Returns an error if the internal channel has been closed.
Sourcepub fn log_server(&self) -> Option<Arc<Mutex<LogServer>>>
pub fn log_server(&self) -> Option<Arc<Mutex<LogServer>>>
log_server returns the shared LogServer registered during build, if any.
The returned Arc<Mutex<LogServer>> is the same instance intercepting /log/*
requests, so callers can inspect or modify log state without additional coordination.
Sourcepub fn anchor_server(&self) -> Option<Arc<Mutex<AnchorServer>>>
pub fn anchor_server(&self) -> Option<Arc<Mutex<AnchorServer>>>
anchor_server returns the shared AnchorServer registered during build, if any.
The returned Arc<Mutex<AnchorServer>> is the same instance intercepting
/checkpoint/* requests.