To create a WebSocket server, you must implement the ServerExt trait. This trait defines how your server handles new connections, disconnections, and custom calls. You also need to define a Session type that implements SessionExt to manage individual client interactions.
- Implement
SessionExt: Define how a session handles text, binary, and custom calls. - Implement
ServerExt: Define on_connect (to create and return a Session), on_disconnect, and on_call (to handle custom messages). - Start the Server: Use
Server::create with a closure that initializes your ServerExt implementation.
use async_trait::async_trait;
use ezsockets::{Server, ServerExt, Session, SessionExt, Socket, Request, Error, CloseFrame};
use std::net::SocketAddr;
type SessionID = u16;
type SessionType = Session<SessionID, ()>;
struct EchoSession {
handle: SessionType,
id: SessionID,
}
#[async_trait]
impl SessionExt for EchoSession {
type ID = SessionID;
type Call = ();
fn id(&self) -> &Self::ID {
&self.id
}
async fn on_text(&mut self, text: ezsockets::Utf8Bytes) -> Result<(), Error> {
self.handle.text(text);
Ok(())
}
async fn on_binary(&mut self, _bytes: ezsockets::Bytes) -> Result<(), Error> {
unimplemented!()
}
async fn on_call(&mut self, _call: Self::Call) -> Result<(), Error> {
Ok(())
}
}
struct EchoServer;
#[async_trait]
impl ServerExt for EchoServer {
type Session = EchoSession;
type Call = ();
async fn on_connect(
&mut self,
socket: Socket,
request: Request,
address: SocketAddr,
) -> Result<SessionType, Option<CloseFrame>> {
let id = address.port();
let session = Session::create(|handle| EchoSession { id, handle }, id, socket);
Ok(session)
}
async fn on_disconnect(
&mut self,
_id: <Self::Session as SessionExt>::ID,
_reason: Result<Option<CloseFrame>, Error>,
) -> Result<(), Error> {
Ok(())
}
async fn on_call(&mut self, _call: Self::Call) -> Result<(), Error> {
Ok(())
}
}
#[tokio::main]
async fn main() {
let (server, _handle) = Server::create(|server| EchoServer);
// Use server.accept(...) with a backend like tungstenite or axum
}