Skip to main content

LocalPlayerEvents

Struct LocalPlayerEvents 

Source
pub struct LocalPlayerEvents(pub UnboundedSender<Event>);
Expand description

A component that contains an event sender for events that are only received by local players.

The receiver for this is returned by Client::start_client.

Tuple Fields§

§0: UnboundedSender<Event>

Methods from Deref<Target = UnboundedSender<Event>>§

pub fn send(&self, message: T) -> Result<(), SendError<T>>

Attempts to send a message on this UnboundedSender without blocking.

This method is not marked as async because sending a message to an unbounded channel never requires any form of waiting. This is due to the channel’s infinite capacity, allowing the send operation to complete immediately. As a result, the send method can be used in both synchronous and asynchronous code without issues.

If the receive half of the channel is closed, either due to close being called or the UnboundedReceiver having been dropped, this function returns an error. The error includes the value passed to send.

Examples found in repository?
azalea-protocol/examples/packet_logger.rs (line 458)
217async fn proxy_conn(
218    mut client_conn: Connection<ServerboundLoginPacket, ClientboundLoginPacket>,
219) -> Result<(), Box<dyn Error>> {
220    // resolve TARGET_ADDR
221    let parsed_target_addr = ServerAddr::from_str(TARGET_ADDR).unwrap();
222    let resolved_target_addr = resolve_address(&parsed_target_addr).await?;
223
224    let mut server_conn = Connection::new(&resolved_target_addr).await?;
225
226    let account = if ACCOUNT.contains('@') {
227        Account::microsoft(ACCOUNT).await?
228    } else {
229        Account::offline(ACCOUNT)
230    };
231    println!("got account: {:?}", account);
232
233    server_conn
234        .write(
235            Default::default(),
236            ServerboundIntention {
237                protocol_version: PROTOCOL_VERSION,
238                hostname: parsed_target_addr.host,
239                port: parsed_target_addr.port,
240                intention: ClientIntention::Login,
241            },
242        )
243        .await?;
244    let mut server_conn = server_conn.login();
245
246    // login
247    server_conn
248        .write(
249            Default::default(),
250            ServerboundHello {
251                name: account.username().to_owned(),
252                profile_id: account.uuid(),
253            },
254        )
255        .await?;
256
257    let (server_conn, login_finished) = loop {
258        let packet = server_conn.read(Default::default()).await?;
259
260        println!("got packet: {:?}", packet);
261
262        match packet {
263            ClientboundLoginPacket::Hello(p) => {
264                debug!("Got encryption request");
265                let e = azalea_crypto::encrypt(&p.public_key, &p.challenge).unwrap();
266
267                if let Some(access_token) = account.access_token() {
268                    // keep track of the number of times we tried
269                    // authenticating so we can give up after too many
270                    let mut attempts: usize = 1;
271
272                    while let Err(e) = {
273                        server_conn
274                            .authenticate(&access_token, &account.uuid(), e.secret_key, &p, None)
275                            .await
276                    } {
277                        if attempts >= 2 {
278                            // if this is the second attempt and we failed
279                            // both times, give up
280                            return Err(e.into());
281                        }
282                        if matches!(
283                            e,
284                            ClientSessionServerError::InvalidSession
285                                | ClientSessionServerError::ForbiddenOperation
286                        ) {
287                            // uh oh, we got an invalid session and have
288                            // to reauthenticate now
289                            account.refresh().await?;
290                        } else {
291                            return Err(e.into());
292                        }
293                        attempts += 1;
294                    }
295                }
296
297                server_conn
298                    .write(
299                        Default::default(),
300                        ServerboundKey {
301                            key_bytes: e.encrypted_public_key,
302                            encrypted_challenge: e.encrypted_challenge,
303                        },
304                    )
305                    .await?;
306
307                server_conn.set_encryption_key(e.secret_key);
308            }
309            ClientboundLoginPacket::LoginCompression(p) => {
310                debug!("Got compression request {:?}", p.compression_threshold);
311                server_conn.set_compression_threshold(p.compression_threshold);
312            }
313            ClientboundLoginPacket::LoginFinished(p) => {
314                debug!(
315                    "Got profile {:?}. handshake is finished and we're now switching to the configuration state",
316                    p.game_profile
317                );
318                // server_conn.write(Default::default(),
319                // ServerboundLoginAcknowledged {}).await?;
320                break (server_conn.config(), p);
321            }
322            ClientboundLoginPacket::LoginDisconnect(p) => {
323                error!("Got disconnect {p:?}");
324                return Err("Disconnected".into());
325            }
326            ClientboundLoginPacket::CustomQuery(p) => {
327                debug!("Got custom query {:?}", p);
328                // replying to custom query is done in
329                // packet_handling::login::process_packet_events
330            }
331            ClientboundLoginPacket::CookieRequest(p) => {
332                debug!("Got cookie request {:?}", p);
333
334                server_conn
335                    .write(
336                        Default::default(),
337                        packets::login::ServerboundCookieResponse {
338                            key: p.key,
339                            // cookies aren't implemented
340                            payload: None,
341                        },
342                    )
343                    .await?;
344            }
345        }
346    };
347
348    // give the client the login_finished
349    println!("got the login_finished: {:?}", login_finished);
350    client_conn
351        .write(Default::default(), login_finished)
352        .await?;
353    let client_conn = client_conn.config();
354
355    info!("started direct bridging");
356
357    // bridge packets
358    let listen_raw_reader = client_conn.reader.raw;
359    let listen_raw_writer = client_conn.writer.raw;
360
361    let target_raw_reader = server_conn.reader.raw;
362    let target_raw_writer = server_conn.writer.raw;
363
364    let packet_logs_txt = Arc::new(tokio::sync::Mutex::new(
365        File::create("combined.txt").await.unwrap(),
366    ));
367
368    let packet_logs_txt_clone = packet_logs_txt.clone();
369    let copy_listen_to_target = tokio::spawn(async move {
370        let mut listen_raw_reader = listen_raw_reader;
371        let mut target_raw_writer = target_raw_writer;
372
373        let packet_logs_txt = packet_logs_txt_clone;
374
375        let mut serverbound_parsed_txt = File::create("serverbound.txt").await.unwrap();
376
377        loop {
378            let packet = match listen_raw_reader.read().await {
379                Ok(p) => p,
380                Err(e) => {
381                    error!("Error reading packet from listen: {e}");
382                    return;
383                }
384            };
385
386            // decode as a game packet
387            let decoded_packet = azalea_protocol::read::deserialize_packet::<ServerboundGamePacket>(
388                Default::default(),
389                &mut Cursor::new(&packet),
390            );
391
392            if let Ok(decoded_packet) = decoded_packet {
393                let timestamp = chrono::Utc::now();
394                let _ = serverbound_parsed_txt
395                    .write_all(format!("{timestamp} {:?}\n", decoded_packet).as_bytes())
396                    .await;
397                let _ = packet_logs_txt
398                    .lock()
399                    .await
400                    .write_all(format!("{timestamp} <- {:?}\n", decoded_packet).as_bytes())
401                    .await;
402            }
403
404            match target_raw_writer.write(Default::default(), &packet).await {
405                Ok(_) => {}
406                Err(e) => {
407                    error!("Error writing packet to target: {e}");
408                    return;
409                }
410            }
411        }
412    });
413
414    // write to clientbound.txt in a separate task so it doesn't block receiving
415    // packets
416    let (clientbound_tx, mut clientbound_rx) = tokio::sync::mpsc::unbounded_channel::<Box<[u8]>>();
417    let copy_clientbound_to_file = tokio::spawn(async move {
418        let mut clientbound_parsed_txt = File::create("clientbound.txt").await.unwrap();
419
420        loop {
421            let Some(packet) = clientbound_rx.recv().await else {
422                return;
423            };
424
425            // decode as a game packet
426            let decoded_packet = azalea_protocol::read::deserialize_packet::<ClientboundGamePacket>(
427                Default::default(),
428                &mut Cursor::new(&packet),
429            );
430
431            if let Ok(decoded_packet) = decoded_packet {
432                let timestamp = chrono::Utc::now();
433                let _ = clientbound_parsed_txt
434                    .write_all(format!("{timestamp} {decoded_packet:?}\n").as_bytes())
435                    .await;
436                let _ = packet_logs_txt
437                    .lock()
438                    .await
439                    .write_all(format!("{timestamp} -> {decoded_packet:?}\n").as_bytes())
440                    .await;
441            }
442        }
443    });
444
445    let copy_remote_to_local = tokio::spawn(async move {
446        let mut target_raw_reader = target_raw_reader;
447        let mut listen_raw_writer = listen_raw_writer;
448
449        loop {
450            let packet = match target_raw_reader.read().await {
451                Ok(p) => p,
452                Err(e) => {
453                    error!("Error reading packet from target: {e}");
454                    return;
455                }
456            };
457
458            clientbound_tx.send(packet.clone()).unwrap();
459
460            match listen_raw_writer.write(Default::default(), &packet).await {
461                Ok(_) => {}
462                Err(e) => {
463                    error!("Error writing packet to listen: {e}");
464                    return;
465                }
466            }
467        }
468    });
469
470    tokio::try_join!(
471        copy_listen_to_target,
472        copy_remote_to_local,
473        copy_clientbound_to_file
474    )?;
475
476    Ok(())
477}

pub async fn closed(&self)

Completes when the receiver has dropped.

This allows the producers to get notified when interest in the produced values is canceled and immediately stop doing work.

§Cancel safety

This method is cancel safe. Once the channel is closed, it stays closed forever and all future calls to closed will return immediately.

§Examples
use tokio::sync::mpsc;

let (tx1, rx) = mpsc::unbounded_channel::<()>();
let tx2 = tx1.clone();
let tx3 = tx1.clone();
let tx4 = tx1.clone();
let tx5 = tx1.clone();
tokio::spawn(async move {
    drop(rx);
});

futures::join!(
    tx1.closed(),
    tx2.closed(),
    tx3.closed(),
    tx4.closed(),
    tx5.closed()
);
println!("Receiver dropped");

pub fn is_closed(&self) -> bool

Checks if the channel has been closed. This happens when the UnboundedReceiver is dropped, or when the UnboundedReceiver::close method is called.

let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<()>();
assert!(!tx.is_closed());

let tx2 = tx.clone();
assert!(!tx2.is_closed());

drop(rx);
assert!(tx.is_closed());
assert!(tx2.is_closed());

pub fn same_channel(&self, other: &UnboundedSender<T>) -> bool

Returns true if senders belong to the same channel.

§Examples
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<()>();
let  tx2 = tx.clone();
assert!(tx.same_channel(&tx2));

let (tx3, rx3) = tokio::sync::mpsc::unbounded_channel::<()>();
assert!(!tx3.same_channel(&tx2));

pub fn downgrade(&self) -> WeakUnboundedSender<T>

Converts the UnboundedSender to a [WeakUnboundedSender] that does not count towards RAII semantics, i.e. if all UnboundedSender instances of the channel were dropped and only WeakUnboundedSender instances remain, the channel is closed.

pub fn strong_count(&self) -> usize

Returns the number of [UnboundedSender] handles.

pub fn weak_count(&self) -> usize

Returns the number of [WeakUnboundedSender] handles.

Trait Implementations§

Source§

impl Component for LocalPlayerEvents
where Self: Send + Sync + 'static,

Source§

const STORAGE_TYPE: StorageType = bevy_ecs::component::StorageType::Table

A constant indicating the storage type used for this component.
Source§

type Mutability = Mutable

A marker type to assist Bevy with determining if this component is mutable, or immutable. Mutable components will have Component<Mutability = Mutable>, while immutable components will instead have Component<Mutability = Immutable>. Read more
Source§

fn register_required_components( _requiree: ComponentId, required_components: &mut RequiredComponentsRegistrator<'_, '_>, )

Registers required components. Read more
Source§

fn clone_behavior() -> ComponentCloneBehavior

Called when registering this component, allowing to override clone function (or disable cloning altogether) for this component. Read more
Source§

fn relationship_accessor() -> Option<ComponentRelationshipAccessor<Self>>

Returns [ComponentRelationshipAccessor] required for working with relationships in dynamic contexts. Read more
§

fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_add [ComponentHook] for this Component if one is defined.
§

fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_insert [ComponentHook] for this Component if one is defined.
§

fn on_discard() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_discard [ComponentHook] for this Component if one is defined.
§

fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_remove [ComponentHook] for this Component if one is defined.
§

fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_despawn [ComponentHook] for this Component if one is defined.
§

fn map_entities<E>(_this: &mut Self, _mapper: &mut E)
where E: EntityMapper,

Maps the entities on this component using the given [EntityMapper]. This is used to remap entities in contexts like scenes and entity cloning. When deriving Component, this is populated by annotating fields containing entities with #[entities] Read more
§

const HAS_SUMMARY_TICK: bool = false

Set this constant to true if the component should track a summary tick. Read more
Source§

impl Deref for LocalPlayerEvents

Source§

type Target = UnboundedSender<Event>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl DerefMut for LocalPlayerEvents

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.

Auto Trait Implementations§

§

impl Forget for LocalPlayerEvents

§

impl Freeze for LocalPlayerEvents
where *const ArcInner<Chan<Event, Semaphore>> is !null: Freeze, PhantomData<ArcInner<Chan<Event, Semaphore>>>: Freeze,

§

impl Move for LocalPlayerEvents

§

impl RefUnwindSafe for LocalPlayerEvents
where Atomic<usize>: RefUnwindSafe, Chan<Event, Semaphore>: RefUnwindSafe,

§

impl Send for LocalPlayerEvents
where Arc<Chan<Event, Semaphore>>: Send,

§

impl Sync for LocalPlayerEvents
where Arc<Chan<Event, Semaphore>>: Sync,

§

impl Unpin for LocalPlayerEvents
where Arc<Chan<Event, Semaphore>>: Unpin,

§

impl UnsafeUnpin for LocalPlayerEvents
where *const ArcInner<Chan<Event, Semaphore>> is !null: UnsafeUnpin, PhantomData<ArcInner<Chan<Event, Semaphore>>>: UnsafeUnpin,

§

impl UnwindSafe for LocalPlayerEvents
where Arc<Chan<Event, Semaphore>>: UnwindSafe,

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
§

impl<C> Bundle for C
where C: Component,

§

fn component_ids( components: &mut ComponentsRegistrator<'_>, ) -> impl Iterator<Item = ComponentId> + use<C>

§

fn get_component_ids( components: &Components, ) -> impl Iterator<Item = Option<ComponentId>>

Returns an iterator over this [Bundle]’s component ids. This will be None if the component has not been registered.
§

impl<C> BundleFromComponents for C
where C: Component,

§

unsafe fn from_components<T, F>(ctx: &mut T, func: &mut F) -> C
where F: for<'a> FnMut(&'a mut T) -> OwningPtr<'a>, C: Sized,

§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<T> CompatExt for T

§

fn compat(self) -> Compat<T> ⓘ
where T: Sized,

Applies the [Compat] adapter by value. Read more
§

fn compat_ref(&self) -> Compat<&T> ⓘ

Applies the [Compat] adapter by shared reference. Read more
§

fn compat_mut(&mut self) -> Compat<&mut T> ⓘ

Applies the [Compat] adapter by mutable reference. Read more
§

impl<T> ConditionalSend for T
where T: Send,

§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> DowncastSend for T
where T: Any + Send,

§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

impl<C> DynamicBundle for C
where C: Component,

§

type Effect = ()

An operation on the entity that happens after inserting this bundle.
§

unsafe fn get_components( ptr: MovingPtr<'_, C>, func: &mut impl FnMut(StorageType, OwningPtr<'_>), ) -> <C as DynamicBundle>::Effect

Moves the components out of the bundle. Read more
§

unsafe fn apply_effect( _ptr: MovingPtr<'_, MaybeUninit<C>>, _entity: &mut EntityWorldMut<'_>, )

Applies the after-effects of spawning this bundle. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<A, B> Interchangeable<A> for B
where A: From<B>, B: From<A>,

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> IntoResult<T> for T

§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
§

impl<A> Is for A
where A: Any,

§

fn is<T>() -> bool
where T: Any,

Checks if the current type “is” another type, using a TypeId equality comparison. This is most useful in the context of generic logic. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

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

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

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

Source§

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

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more