View Source ElvenGard.Network.Socket (ElvenGard.Network v0.1.1)

Manage a socket.

This module provides functionality for managing a socket in the network protocol. A socket is a connection between the server and a client. It maintains various socket fields, such as the socket ID, socket assigns, transport information, and the packet network encoder used for sending data.

socket-fields

Socket fields

  • :id: The unique string ID of the socket.
  • :assigns: A map of socket assigns, which can be used to store custom data associated with the socket. The default value is %{}.
  • :transport: The Ranch transport used for the socket.
  • :transport_pid: The PID (Process ID) of the socket's transport process.
  • :remaining: The remaining bytes after receiving and packet deserialization.
  • :encoder: The ElvenGard.Network.NetworkCodec module used to encode packets in the send/2 function.

Link to this section Summary

Functions

Adds key value pairs to socket assigns.

Create a new socket structure.

Send a packet to the client.

Link to this section Types

@type t() :: %ElvenGard.Network.Socket{
  assigns: map(),
  encoder: module() | :unset,
  id: String.t(),
  remaining: bitstring(),
  transport: atom(),
  transport_pid: pid()
}

Link to this section Functions

@spec assign(t(), map() | keyword()) :: t()
Link to this function

assign(socket, key, value)

View Source
@spec assign(t(), atom(), any()) :: t()

Adds key value pairs to socket assigns.

A single key value pair may be passed, a keyword list or map of assigns may be provided to be merged into existing socket assigns.

examples

Examples

iex> assign(socket, :name, "ElvenGard")
iex> socket.assigns.name == "ElvenGard"
true

iex> assign(socket, name: "ElvenGard", logo: "🌸")
iex> socket.assigns.name == "ElvenGard"
true
iex> socket.assigns.logo == "🌸"
true
Link to this function

new(transport_pid, transport, encoder)

View Source
@spec new(pid(), atom(), module()) :: t()

Create a new socket structure.

This function initializes a new socket with the given transport_pid, transport, and encoder module.

@spec send(t(), struct() | iodata()) :: :ok | {:error, atom()}

Send a packet to the client.

This function sends a packet to the client through the socket's transport. If the socket's encoder is set to :unset, the data is sent as is. Otherwise, the encoder module is used to serialize the data before sending it.

examples

Examples

iex> ElvenGard.Network.Socket.send(socket, %LoginResponse{status: 200, message: "Welcome!"})
:ok