Crate bevy_connect

Crate bevy_connect 

Source
Expand description

Channel communication over network. This crate uses TCP for communication.

A new session can be created per every message type. Each of these message types is a connection, and muliple message types will create parallel connections.

Connecions are established in direct mode via host+port. For the host it means binding to that host & port, for the client means to connect to it.

The client has an initial blocking time until it receives an assignment message from the host, which is sent straight away after accepting the tcp connection.

A resourece of type channel::Channel<T> will be present for each of the connection, for each of the different message type T.

Connecting or disconnecting is done by queuing a Command to bevy. commands::SessionConnectCommand<T> will create a new session, like this will create two different sessions each identified by the type of message they are handling, and send and receive messages:

use bevy_app::*;
use bevy_ecs::prelude::*;
use bevy_connect::prelude::*;
use serde::{Serialize, Deserialize};

App::new()
    .add_plugins(SessionPlugin::<Msg>::default())
    .add_systems(Startup, bevy_startup)
    .add_systems(Update, (receive_message, send_message)
        // The presence of the channel resource indicates an established
        // session (connected)
        .run_if(resource_exists::<Channel<Msg>>));

#[derive(Serialize, Deserialize)]
struct Msg {
    data: String
}

#[derive(Serialize, Deserialize)]
struct AnotherDifferentMessageType {
    audio_buffer: Vec<u8>
}

fn bevy_startup(mut cmd: Commands) {
    cmd.queue(SessionConnectCommand::<Msg>::from_config(
        SessionConfig::Direct {
            addr: Some("127.0.0.1".parse().unwrap()),
            port: 6000,
            host: true, // use false for the client side
            options: Default::default(),
        },
    ));
    cmd.queue(SessionConnectCommand::<AnotherDifferentMessageType>::from_config(
        SessionConfig::Direct {
            addr: Some("127.0.0.1".parse().unwrap()),
            port: 7000,
            host: true, // use false for the client side
            options: Default::default(),
        },
    ));
}

fn receive_message(mut events: EventReader<MessageReceivedEvent<Msg>>) {
    for e in events.read() {
        println!("{}", e.message.data);
    }
}

fn send_message(mut channel: ResMut<Channel<Msg>>) {
    channel.broadcast(Msg{data: "hello".to_string()}.into());
}

Using the command commands::SessionDisconnectCommand<T> will disconnect the session for the message type T. The resource channel::Channel<T> will be gone once disconnection is complete.

Modules§

channel
commands
events
prelude

Structs§

SessionPlugin
Add this plugin (unique by type T) to the app to first setup the channel for the message type T.

Traits§

Message