cg_game_server/
socket.rs

1//! This module helps implement your own CodeGame WebSocket endpoint.
2//!
3//! For examples see [the official games](https://github.com/orgs/code-game-project/teams/games/repositories)
4
5use crate::events::EventWrapper;
6use crate::server_communications::GameServerCommunications;
7use actix::{Actor, Addr, Handler, StreamHandler};
8use actix_web_actors::ws;
9use std::time::Duration;
10
11// constants to be used in each implementation of `Socket`
12/// default websocket heartbeat interval
13pub const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
14/// default websocket heartbeat timeout
15pub const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
16/// constant id to be used when the socket is sending the client it's connected to something
17pub const SOCKET_SELF_ID: &str = "self";
18
19/// A generic game socket that can be implemented and extended to fit any game's needs
20pub trait Socket<G, S, R>
21where
22  Self: Actor,
23  Self: StreamHandler<Result<ws::Message, ws::ProtocolError>>,
24  Self: Handler<EventWrapper<S>>,
25  Self: GameServerCommunications<G, S>,
26  G: Actor,
27{
28  /// Creates and returns new instance of `Socket`
29  fn new(gs: Addr<G>) -> Self;
30  /// Starts the websocket heartbeat
31  fn hb(&self, ctx: &mut <Self as Actor>::Context)
32  where
33    Self: actix::Actor;
34  /// Wraps a receivable game event `R` (from self, to self) and emits it
35  ///
36  /// This can be used for events such as errors that come from the socket and go
37  /// to the associated client
38  fn self_emit(ctx: &mut <Self as Actor>::Context, event: S)
39  where
40    Self: actix::Actor;
41  /// Serializes and sends a receiveable game event `R` to `ctx`
42  fn emit(ctx: &mut <Self as Actor>::Context, wrapped: &EventWrapper<S>)
43  where
44    Self: actix::Actor;
45  /// Handles a receivable game event `R` sent to the `Socket` by the client
46  fn handle_receiveable(&mut self, ctx: &mut <Self as Actor>::Context, event: R)
47  where
48    Self: actix::Actor;
49  /// Handles a sendable game event `S` sent to the `Socket` by the game server `G` or another `Socket`
50  fn handle_sendable(&mut self, ctx: &mut <Self as Actor>::Context, wrapped: EventWrapper<S>)
51  where
52    Self: actix::Actor;
53}