pub struct NetworkController { /* private fields */ }
Expand description

Shareable instance in charge of control all the connections.

Implementations§

source§

impl NetworkController

source

pub fn connect( &self, transport: Transport, addr: impl ToRemoteAddr ) -> Result<(Endpoint, SocketAddr)>

Creates a connection to the specified address. The endpoint, an identifier of the new connection, will be returned. This function will generate a NetEvent::Connected event with the result of the connection. This call will NOT block to perform the connection.

Note that this function can return an error in the case the internal socket could not be binded or open in the OS, but never will return an error an regarding the connection itself. If you want to check if the connection has been established or not you have to read the boolean indicator in the NetEvent::Connected event.

Example

use message_io::node::{self, NodeEvent};
use message_io::network::{Transport, NetEvent};

let (handler, listener) = node::split();
handler.signals().send_with_timer((), std::time::Duration::from_secs(1));

let (id, addr) = handler.network().listen(Transport::FramedTcp, "127.0.0.1:0").unwrap();
let (conn_endpoint, _) = handler.network().connect(Transport::FramedTcp, addr).unwrap();
// The socket could not be able to send yet.

listener.for_each(move |event| match event {
    NodeEvent::Network(net_event) => match net_event {
        NetEvent::Connected(endpoint, established) => {
            assert_eq!(conn_endpoint, endpoint);
            if established {
                println!("Connected!");
                handler.network().send(endpoint, &[42]);
            }
            else {
                println!("Could not connect");
            }
        },
        NetEvent::Accepted(endpoint, listening_id) => {
            assert_eq!(id, listening_id);
            println!("New connected endpoint: {}", endpoint.addr());
        },
        _ => (),
    }
    NodeEvent::Signal(_) => handler.stop(),
});
source

pub fn connect_with( &self, transport_connect: TransportConnect, addr: impl ToRemoteAddr ) -> Result<(Endpoint, SocketAddr)>

Creates a connection to the specified address with custom transport options for transports that support it. The endpoint, an identifier of the new connection, will be returned. This function will generate a NetEvent::Connected event with the result of the connection. This call will NOT block to perform the connection.

Note that this function can return an error in the case the internal socket could not be binded or open in the OS, but never will return an error regarding the connection itself. If you want to check if the connection has been established or not you have to read the boolean indicator in the NetEvent::Connected event.

Example

use message_io::node::{self, NodeEvent};
use message_io::network::{TransportConnect, NetEvent};
use message_io::adapters::udp::{UdpConnectConfig};

let (handler, listener) = node::split();
handler.signals().send_with_timer((), std::time::Duration::from_secs(1));

let config = UdpConnectConfig::default().with_broadcast();
let addr = "255.255.255.255:7777";
let (conn_endpoint, _) = handler.network().connect_with(TransportConnect::Udp(config), addr).unwrap();
// The socket could not be able to send yet.

listener.for_each(move |event| match event {
    NodeEvent::Network(net_event) => match net_event {
        NetEvent::Connected(endpoint, established) => {
            assert_eq!(conn_endpoint, endpoint);
            if established {
                println!("Connected!");
                handler.network().send(endpoint, &[42]);
            }
            else {
                println!("Could not connect");
            }
        },
        _ => (),
    }
    NodeEvent::Signal(_) => handler.stop(),
});
source

pub fn connect_sync( &self, transport: Transport, addr: impl ToRemoteAddr ) -> Result<(Endpoint, SocketAddr)>

Creates a connection to the specified address. This function is similar to NetworkController::connect() but will block until for the connection is ready. If the connection can not be established, a ConnectionRefused error will be returned.

Note that the Connect event will be also generated.

Since this function blocks the current thread, it must NOT be used inside the network callback because the internal event could not be processed.

In order to get the best scalability and performance, use the non-blocking NetworkController::connect() version.

Example

use message_io::node::{self, NodeEvent};
use message_io::network::{Transport, NetEvent};

let (handler, listener) = node::split();
handler.signals().send_with_timer((), std::time::Duration::from_secs(1));

let (id, addr) = handler.network().listen(Transport::FramedTcp, "127.0.0.1:0").unwrap();
match handler.network().connect_sync(Transport::FramedTcp, addr) {
    Ok((endpoint, _)) => {
        println!("Connected!");
        handler.network().send(endpoint, &[42]);
    }
    Err(err) if err.kind() == std::io::ErrorKind::ConnectionRefused => {
        println!("Could not connect");
    }
    Err(err) => println!("An OS error creating the socket"),
}
source

pub fn connect_sync_with( &self, transport_connect: TransportConnect, addr: impl ToRemoteAddr ) -> Result<(Endpoint, SocketAddr)>

Creates a connection to the specified address with custom transport options for transports that support it. This function is similar to NetworkController::connect_with() but will block until for the connection is ready. If the connection can not be established, a ConnectionRefused error will be returned.

Note that the Connect event will be also generated.

Since this function blocks the current thread, it must NOT be used inside the network callback because the internal event could not be processed.

In order to get the best scalability and performance, use the non-blocking NetworkController::connect_with() version.

Example

use message_io::node::{self, NodeEvent};
use message_io::network::{TransportConnect, NetEvent};
use message_io::adapters::udp::{UdpConnectConfig};

let (handler, listener) = node::split();
handler.signals().send_with_timer((), std::time::Duration::from_secs(1));

let config = UdpConnectConfig::default().with_broadcast();
let addr = "255.255.255.255:7777";
match handler.network().connect_sync_with(TransportConnect::Udp(config), addr) {
    Ok((endpoint, _)) => {
        println!("Connected!");
        handler.network().send(endpoint, &[42]);
    }
    Err(err) if err.kind() == std::io::ErrorKind::ConnectionRefused => {
        println!("Could not connect");
    }
    Err(err) => println!("An OS error creating the socket"),
}
source

pub fn listen( &self, transport: Transport, addr: impl ToSocketAddrs ) -> Result<(ResourceId, SocketAddr)>

Listen messages from specified transport. The given address will be used as interface and listening port. If the port can be opened, a ResourceId identifying the listener is returned along with the local address, or an error if not. The address is returned despite you passed as parameter because when a 0 port is specified, the OS will give choose the value.

source

pub fn listen_with( &self, transport_listen: TransportListen, addr: impl ToSocketAddrs ) -> Result<(ResourceId, SocketAddr)>

Listen messages from specified transport with custom transport options for transports that support it. The given address will be used as interface and listening port. If the port can be opened, a ResourceId identifying the listener is returned along with the local address, or an error if not. The address is returned despite you passed as parameter because when a 0 port is specified, the OS will give choose the value.

source

pub fn send(&self, endpoint: Endpoint, data: &[u8]) -> SendStatus

Send the data message thought the connection represented by the given endpoint. This function returns a SendStatus indicating the status of this send. There is no guarantee that send over a correct connection generates a SendStatus::Sent because any time a connection can be disconnected (even while you are sending). Except cases where you need to be sure that the message has been sent, you will want to process a NetEvent::Disconnected to determine if the connection + is alive instead of check if send() returned SendStatus::ResourceNotFound.

source

pub fn remove(&self, resource_id: ResourceId) -> bool

Remove a network resource. Returns false if the resource id doesn’t exists. This is used to remove resources as connection or listeners. Resources of endpoints generated by listening in connection oriented transports can also be removed to close the connection. Removing an already connected connection implies a disconnection. Note that non-oriented connections as UDP use its listener resource to manage all remote endpoints internally, the remotes have not resource for themselfs. It means that all generated Endpoints share the ResourceId of the listener and if you remove this resource you are removing the listener of all of them. For that cases there is no need to remove the resource because non-oriented connections have not connection itself to close, ‘there is no spoon’.

source

pub fn is_ready(&self, resource_id: ResourceId) -> Option<bool>

Check a resource specified by resource_id is ready. If the status is true means that the resource is ready to use. In connection oriented transports, it implies the resource is connected. If the status is false it means that the resource is not yet ready to use. If the resource has been removed, disconnected, or does not exists in the network, a None is returned.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V