Struct memsocket::MemoryListener
source · pub struct MemoryListener { /* private fields */ }
Expand description
An in-memory socket server, listening for connections.
After creating a MemoryListener
by bind
ing it to a socket address, it listens
for incoming connections. These can be accepted by awaiting elements from the
async stream of incoming connections, incoming
.
The socket will be closed when the value is dropped.
Examples
use std::io::Result;
use memsocket::{MemoryListener, MemorySocket};
use futures::prelude::*;
async fn write_stormlight(mut stream: MemorySocket) -> Result<()> {
let msg = b"The most important step a person can take is always the next one.";
stream.write_all(msg).await?;
stream.flush().await
}
async fn listen() -> Result<()> {
let mut listener = MemoryListener::bind(16)?;
let mut incoming = listener.incoming();
// accept connections and process them serially
while let Some(stream) = incoming.next().await {
write_stormlight(stream?).await?;
}
Ok(())
}
Implementations§
source§impl MemoryListener
impl MemoryListener
sourcepub fn bind(port: u16) -> Result<Self>
pub fn bind(port: u16) -> Result<Self>
Creates a new MemoryListener
which will be bound to the specified
port.
The returned listener is ready for accepting connections.
Binding with a port number of 0 will request that a port be assigned
to this listener. The port allocated can be queried via the
local_addr
method.
Examples
Create a MemoryListener bound to port 16:
use memsocket::MemoryListener;
let listener = MemoryListener::bind(16)?;
sourcepub fn local_addr(&self) -> u16
pub fn local_addr(&self) -> u16
Returns the local address that this listener is bound to.
This can be useful, for example, when binding to port 0 to figure out which port was actually bound.
Examples
use memsocket::MemoryListener;
let listener = MemoryListener::bind(16)?;
assert_eq!(listener.local_addr(), 16);
sourcepub fn incoming(&mut self) -> Incoming<'_>
pub fn incoming(&mut self) -> Incoming<'_>
Consumes this listener, returning a stream of the sockets this listener accepts.
This method returns an implementation of the Stream
trait which
resolves to the sockets the are accepted on this listener.
Examples
use futures::prelude::*;
use memsocket::MemoryListener;
let mut listener = MemoryListener::bind(16)?;
let mut incoming = listener.incoming();
// accept connections and process them serially
while let Some(stream) = incoming.next().await {
match stream {
Ok(stream) => {
println!("new connection!");
},
Err(e) => { /* connection failed */ }
}
}