pub struct Server<S, R>{ /* private fields */ }Expand description
A socket server.
The server takes two generic parameters:
S: the type of data that will be sent to clients.R: the type of data that will be received from clients.
Both types must be serializable in order to be sent through the socket. When creating clients, the types should be swapped, since the server’s send type will be the client’s receive type and vice versa.
use rustdtp::*;
#[tokio::main]
async fn main() {
// Create a server that receives strings and returns the length of each string
let (mut server, mut server_events) = Server::builder()
.sending::<usize>()
.receiving::<String>()
.with_event_channel()
.start(("0.0.0.0", 0))
.await
.unwrap();
// Iterate over events
while let Some(event) = server_events.next().await {
match event {
ServerEvent::Connect { client_id } => {
println!("Client with ID {} connected", client_id);
}
ServerEvent::Disconnect { client_id } => {
println!("Client with ID {} disconnected", client_id);
}
ServerEvent::Receive { client_id, data } => {
// Send back the length of the string
server.send(client_id, data.len()).await.unwrap();
}
ServerEvent::Stop => {
// No more events will be sent, and the loop will end
println!("Server closed");
}
}
}
}Implementations§
source§impl Server<(), ()>
impl Server<(), ()>
sourcepub fn builder(
) -> ServerBuilder<ServerSendingUnknown, ServerReceivingUnknown, ServerEventReportingUnknown>
pub fn builder( ) -> ServerBuilder<ServerSendingUnknown, ServerReceivingUnknown, ServerEventReportingUnknown>
Constructs a server builder. Use this for a clearer, more explicit,
and more featureful server configuration. See ServerBuilder for
more information.
source§impl<S, R> Server<S, R>
impl<S, R> Server<S, R>
sourcepub async fn start<A>(
addr: A
) -> Result<(ServerHandle<S>, EventStream<ServerEvent<R>>)>where
A: ToSocketAddrs,
pub async fn start<A>(
addr: A
) -> Result<(ServerHandle<S>, EventStream<ServerEvent<R>>)>where
A: ToSocketAddrs,
Start a socket server.
addr: the address for the server to listen on.
Returns a result containing a handle to the server and a channel from which to receive server events, or the error variant if an error occurred while starting the server.
use rustdtp::*;
#[tokio::main]
async fn main() {
let (mut server, mut server_events) = Server::builder()
.sending::<()>()
.receiving::<()>()
.with_event_channel()
.start(("0.0.0.0", 0))
.await
.unwrap();
}Neither the server handle nor the event receiver should be dropped until the server has been stopped. Prematurely dropping either one can cause unintended behavior.