[enet-cvs] CVS: enet api.txt,NONE,1.1 tutorial.txt,NONE,1.1 enet.txt,1.2,NONE

Lee Salzman enet-discuss@lists.puremagic.com
Fri, 7 Mar 2003 13:14:00 -0700


Update of /home/enet/cvsroot/enet
In directory sferik:/tmp/cvs-serv5553

Added Files:
	api.txt tutorial.txt 
Removed Files:
	enet.txt 
Log Message:
Renamed enet.txt to api.txt and added a tutorial.txt


--- NEW FILE: api.txt ---
<enet/enet.h> - The file that should be included to use the ENet API.

uint8 - unsigned 8 bit integer
uint16 - unsigned 16 bit integer
uint32 - unsigned 32 bit integer

typedef struct
{  
  uint32 host; 
  uint16 port; 
} ENetAddress;
      
  Portable internet address structure. The host must be specified in network 
byte-order, and the port must be in host byte-order. The constant ENET_HOST_ANY
may be used to specify the default server host.

typedef struct
{
  uint32 flags;
  uint8 * data;
  size_t dataLength;
} ENetPacket;

  An ENet data packet that may be sent to or received from a peer. The shown fields
should only be read and never modified. The data field contains the allocated data
for the packet. The dataLength fields specifies the length of the allocated data.
The flags field is either 0 (specifying no flags), or a bitwise-or of any
combination of the following flags:
  
  ENET_PACKET_FLAG_RELIABLE -   
  
      Specifies that the packet must be received by the target peer and that resend
    attempts should be made should delivery of the packet fail.

typedef struct
{
  ENetAddress address;
  void * data;
  size_t channelCount;
  uint32 incomingBandwidth;
  uint32 outgoingBandwidth;
  uint32 roundTripTime;
  uint32 packetLoss;
} ENetPeer;

  An ENet peer which data packets may be sent or received from. No fields should be
modified unless otherwise specified. The address field contains the internet address 
of the peer. The data fields may be used to associate any desired data with the peer 
and may be freely modified. The channelCount field tells the number of channels that
have been allocated for use to communnicate with the peer. The incomingBandwidth field
specifies the downstream bandwidth of the client in bytes per second. The 
outgoingBandwidth field specifies the upstream bandwidth of the client in bytes per
second. The roundTripTime field tells the mean round trip time from the sending of
a reliable packet until the receipt of its acknowledgement in milliseconds. The
packetLoss field tells the mean packet loss of reliable packets as a ratio with
respect to the constant ENET_PEER_PACKET_LOSS_SCALE.

typedef enum
{
   ENET_EVENT_TYPE_NONE,
   ENET_EVENT_TYPE_CONNECT,
   ENET_EVENT_TYPE_DISCONNECT,
   ENET_EVENT_TYPE_RECEIVE
} ENetEventType;

typedef struct _ENetEvent
{
   ENetEventType        type;
   ENetPeer *           peer;
   uint8                channelID;
   ENetPacket *         packet;
} ENetEvent;

  An ENet event as returned by enet_host_service. The type field contains the type
of the event, which may be any one of the following:
  
  ENET_EVENT_TYPE_NONE - No event occurred within the specified time limit.
  ENET_EVENT_TYPE_CONNECT - 
    
    A connection request initiated by enet_host_connect has completed. The peer field
  contains the peer which successfully connected.

  ENET_EVENT_TYPE_DISCONNECT -
    
    A peer has disconnected. This event is generated on successful completion of a
  disconnect iniated by enet_peer_disconnect, if a peer has timed out, or if a
  connection request initialized by enet_host_connect has timed out. The peer field
  contains the peer which disconnected.

  ENET_EVENT_TYPE_RECEIVE -
    
    A packet has been received from a peer. The peer field specifies the peer which
  send the packet. The channelID field specifies the channel number upon which the
  packet was received. The packet field contains the packet that was destroyed; this
  packet must be destroyed with enet_packet_destroy after use.

typedef struct
{
  ENetAddress address;
  uint32 incomingBandwidth;
  uint32 outgoingBandwidth;
  ENetPeer * peers;
  size_t peerCount;
} ENetHost;

  An ENet host for communicating with peers. No fields should be modified. The address 
field tells the internet address of the host. The incomingBandwidth field tells the downstream
bandwidth of the host. The outgoingBandwidth field specifies the upstream bandwidth of the host.
The peers field contains an array of the peers that have been allocated for this host. The 
peerCount field specifies the number of peers that have been allocated for this host.

unsigned ENET_HOST_TO_NET_8 (unsigned);
unsigned ENET_HOST_TO_NET_16 (unsigned);
unsigned ENET_HOST_TO_NET_32 (unsigned);

  Macros that convert from host byte-order to network byte-order (big
endian) for unsigned integers of 8 bits, 16 bits, and 32 bits repectively. 

unsigned ENET_NET_TO_HOST_8 (unsigned);
unsigned ENET_NET_TO_HOST_16 (unsigned);
unsigned ENET_NET_TO_HOST_32 (unsigned);

  Macros that convert from network byte-order (big endian) to host 
byte-order for unsigned integers of 8 bits, 16 bits, and 32 bits repectively.

uint32 enet_time_get (void);

  Returns the wall-time in milliseconds. Its initial value is unspecified unless
otherwise set.

void enet_time_set (uint32);

  Sets the current wall-time in milliseconds.

int enet_initialize (void);

  Initialize ENet for use. Must be called prior to using any functions in ENet.
Returns 0 on success and -1 on failure.

void enet_deinitialize (void);

  Clean-up ENet after use. Should be called when a program that has initialized
and used ENet exits.

int enet_address_set_host (ENetAddress * address, const char * hostName);

  Attempts to resolve the host named by the parameter hostName and sets the host
field in the address parameter if successful. Returns 0 on success and -1 on
failure.

int enet_address_get_host (const ENetAddress * address, char * hostName, size_t nameLength);

  Attempts to do a reverse lookup of the host field in the address parameter.
If successful, the name of the host is placed in the string described by
hostName and nameLength. The host name is always null-delimited and will
not exceed nameLength in length. Returns 0 on success and -1 on failure.

ENetPacket * enet_packet_create (const void * dataContents, size_t dataLength, uint32 flags);

  Creates a packet that may be sent to a peer. The dataContents parameter
specifies the initial contents of the packet's data; the packet's data will
remain uninitialized if dataContents is NULL. The dataLength parameter specifies
the size of the data that is allocated for this packet. The flags parameter
specifies flags for this packet as described for the ENetPacket structure.
Returns the packet on success and NULL on failure.

void enet_packet_destroy (ENetPacket * packet);

  Destroys the packet and deallocates its data.

int enet_packet_resize (ENetPacket * packet, size_t dataLength);

  Attempts to resize the data in the packet to the length specified in the
dataLength parameter. Returns 0 on success and -1 on failure.

ENetHost * enet_host_create (const ENetAddress * address, size_t peerCount, uint32 incomingBandwidth, uint32 outgoingBandwidth);

  Creates a host for communicating with peers. The address parameter specifies 
the address at which other peers may connect to this host; if the address parameter
is NULL, then no peers may connect to the host. The peerCount parameter specifies
the numbers of peers that should be allocated for the host; this limits the maximum
number of peers that may connect to this host to peerCount. The incomingBandwidth
parameter specifies the downstream bandwidth of the host in bytes per second; if
the incomingBandwidth parameter is 0, ENet will assume the host has unlimited
downstream bandwidth. The outgoingBandwidth parameter specifies the upstream bandwidth
of the host in bytes per second; if the outgoingBandwidth parameter is 0, ENet will
assume the host has unlimited upstream bandwidth. ENet will strategically drop packets
on specific sides of a connection between hosts to ensure the host's bandwidth is not
overwhelmed; the bandwidth parameters also determine the window size of a connection
which limits the amount of reliable packets that may be in transit at any given time.
Returns the host on success and NULL on failure.

void enet_host_destroy (ENetHost * host);

  Destroys the host and all resources associated with it.

ENetPeer * enet_host_connect (ENetHost * host, const ENetAddress * address, size_t channelCount);
  
  Initiates a connection from the host specified in the host parameter to a foreign 
host whose internet address is specified by the address parameter. The channelCount 
parameter specifies the number of channels that should be allocated for communicating 
with the foreign host. Returns a peer representing the foreign host on success and NULL
on failure. The peer returned will have not completed the connection until enet_host_service
notifies of an ENET_EVENT_TYPE_CONNECT event for the peer.

int enet_host_service (ENetHost * host, ENetEvent * event, uint32 timeout);

  Waits for events on the host specified by the host parameters and shuttles packets 
between the host and its peers. The event parameter specifies an event structure
where event details will be placed if one occurs. The timeout field specifies an
amount of time in milliseconds that ENet should wait for events. Returns 1 if an
event occured within the specified time limit, 0 if no event occurred within the 
time limit, and -1 on failure. This function must be called frequently for adequate
performance.

void enet_host_flush (ENetHost * host);

  Sends out any queued packets on the host specified in the host parameters to
the designated peers. This function need only be used in circumstances where one
wishes to send queued packets earlier than in a call to enet_host_service.

void enet_host_broadcast (ENetHost * host, uint8 channelID, ENetPacket * packet);

  Queues a packet to be sent to all peers on the host specified in the host parameter
over the channel number identified by the channelID parameter.

void enet_host_bandwidth_limit (ENetHost * host, uint32 incomingBandwidth, uint32 outgoingBandwidth);

  Adjusts the bandwidth limits of the host specified in the host parameter. The
incomingBandwidth and outgoingBandwidth parameters are as specified in a call to 
enet_host_create.

int enet_peer_send (ENetPeer * peer, uint8 channelID, ENetPacket * packet);

  Queues a packet to be sent to the peer specified by the peer parameter over the
channel number identified by the channelID parameter. Returns 0 on success and -1
on failure.

ENetPacket * enet_peer_receive (ENetPeer * peer, uint8 channelID);

  Attempts to dequeue any incoming queued packets on the peer specified by the peer
parameter on the channel number identified by the channelID parameter. Returns a packet
if one is available and NULL if there are no available incoming queued packets.

void enet_peer_ping (ENetPeer * peer);
  
  Sends a ping request to the peer specified by the peer parameter. Ping requests factor
into the mean round trip time as designated by the roundTripTime field in the ENetPeer
structure. ENet automatically pings all connected peer at an interval, however, this 
function may be called to ensure more frequent ping requests.

void enet_peer_reset (ENetPeer * peer);

  Forcefully disconnects the peer specified by the peer parameter. The foreign host 
represented by the peer is not notified of the disconnection and so will timeout on its
connection to the local host.

void enet_peer_disconnect (ENetPeer * peer);

  Request a disconnection from the peer specified by the peer parameter. An
ENET_EVENT_DISCONNECT event will be generated by enet_host_service once the
disconnection is complete.

void enet_peer_throttle_configure (ENetPeer * peer, uint32 interval, uint32 acceleration, uint32 deceleration);

  Configures throttle parameter for the peer specified by the peer parameter.
Unreliable packets are dropped by ENet in response to the varying conditions of
the internet connection to the peer. The throttle represents a probability that
an unreliable packet should not be dropped and thus sent by ENet to the peer.
The lowest mean round trip time from the sending of a reliable packet to the 
receipt of its acknowledgement is measured over an amount of time specified 
by the interval parameter in milliseconds; the constant ENET_PEER_PACKET_THROTTLE_INTERVAL
is the default value for this parameter. If a measured round trip time happens 
to be signifigantly less than the mean round trip time measured over the interval, 
then the throttle probability is increased to allow more traffic by an amount
specified in the acceleration parameter which is in ratio to the
ENET_PEER_PACKET_THROTTLE_SCALE constant. If a measured round trip time happens
to be signifigantly greater than the mean round trip time measured over the interval,
then the throttle probability is decreased to limit traffic by an amount specified
in the deceleration parameter which is in ratio to the ENET_PEER_PACKET_THROTTLE_SCALE
constant. When the throttle has a value of ENET_PEER_PACKET_THROTTLE_SCALE, no unreliable
packets are dropped by ENET, and so 100% of all unreliable packets will be sent. When the 
throttle has a value of 0, all unreliable packets are dropped by ENet, and so 0% of all
unreliable packets will be sent. Intermediate values for the throttle represent intermediate
probabilities between 0% and 100% of unreliable packets being sent. The bandwidth limits
of the local and foreign host are taken into account to determine a sensible limit for
the throttle probability above which it should not raise even in the best of conditions.




--- NEW FILE: tutorial.txt ---
* Using ENet

    Before using ENet, you must call enet_initialize() to initialize the
library. Upon program exit, you should call enet_deinitialize() so that
the library may clean up any used resources.

i.e.

int 
main (int argc, char ** argv) 
{
    if (enet_initialize () != 0)
    {
        fprintf (stderror, "An error occurred while initializing ENet.\n");
        return EXIT_FAILURE;
    }
    atexit (enet_deinitialize);
    ...
    ...
    ...
}
        
* Creating an ENet server

    Servers in ENet are constructed with enet_host_create(). You must specify
an address on which to receive data and new connections, as well as the maximum
allowable numbers of connected peers. You may optionally specify the incoming
and outgoing bandwidth of the server in bytes per second so that ENet may try
to statically manage bandwidth resources among connected peers in addition to
its dynamic throttling algorithm; specifying 0 for these two options will cause 
ENet to rely entirely upon its dynamic throttling algorithm to manage 
bandwidth.

    When done with a host, the host may be destroyed with enet_host_destroy().
All connectected peers to the host will be reset, and the resources used by
the host will be freed.

i.e.

    ENetAddress address;
    ENetHost * server;

    /* Bind the server to the default localhost.
     * A specific host address can be specified by
     * enet_address_set_host (& address, "x.x.x.x");
     */
    address.host = ENET_HOST_ANY;
    /* Bind the server to port 1234. */
    address.port = 1234;

    server = enet_host_create (& address /* the address to bind the server host to */, 
                32 /* allow up to 32 clients and/or outgoing connections */,
                0 /* assume any amount of incoming bandwidth */,
                0 /* assume any amount of outgoing bandwidth */);
    if (server == NULL)
    {
        fprintf (stderr, 
                 "An error occurred while trying to create an ENet server host.\n");
        exit (EXIT_FAILURE);
    }
    ...
    ...
    ...
    enet_host_destroy(server);

* Creating an ENet client

    Clients in ENet are similarly constructed with enet_host_create() when no
address is specified to bind the host to. Bandwidth may be specified for the 
client host as in the above example. The peer count controls the maximum number
of connections to other server hosts that may be simultaneously open.

i.e.

    ENetHost * client;

    clienet = enet_host_create (NULL /* create a client host */,
                1 /* only allow 1 outgoing connection */,
                57600 / 8 /* 56K modem with 56 Kbps downstream bandwidth */,
                14400 / 8 /* 56K modem with 14 Kbps upstream bandwidth */);

    if (client == NULL)
    {
        fprintf (stderr, 
                 "An error occurred while trying to create an ENet client host.\n");
        exit (EXIT_FAILURE);
    }
    ...
    ...
    ...
    enet_host_destroy(client);

* Managing an ENet host

    ENet uses a polled event model to notify the programmer of significant 
events. ENet hosts are polled for events with enet_host_service(), where an
optional timeout value in milliseconds may be specified to control how long
ENet will poll; if a timeout of 0 is specified, enet_host_service() will
return immediately if there are no events to dispatch. enet_host_service()
will return 1 if an event was dispatched within the specified timeout.

    Currently there are only four types of significant events in ENet:

An event of type ENET_EVENT_TYPE_NONE is returned if no event occurred
within the specified time limit. enet_host_service() will return 0
with this event.

An event of type ENET_EVENT_TYPE_CONNECT is returned when either a new client
host has connected to the server host or when an attempt to establish a 
connection with a foreign host has succeeded. Only the "peer" field of the 
event structure is valid for this event and contains the newly connected peer.

An event of type ENET_EVENT_TYPE_RECEIVE is returned when a packet is received
from a connected peer. The "peer" field contains the peer the packet was 
received from, "channelID" is the channel on which the packet was sent, and 
"packet" is the packet that was sent. The packet contained in the "packet" 
field must be destroyed with enet_packet_destroy() when you are done 
inspecting its contents.

An event of type ENET_EVENT_TYPE_DISCONNECT is returned when a connected peer
has either explicitly disconnected or timed out. Only the "peer" field of the
event structure is valid for this event and contains the peer that 
disconnected. Only the "data" field of the peer is still valid on a 
disconnect event and must be explicitly reset.

i.e.

    ENetEvent event;
    
    /* Wait up to 1000 milliseconds for an event. */
    while (enet_host_service (client, & event, 1000) > 0)
    {
        switch (event.type)
        {
        case ENET_EVENT_TYPE_CONNECT:
            printf ("A new client connected from %x:%u.\n", 
                    event.peer -> address.host,
                    event.peer -> address.port);

            /* Store any relevant client information here. */
            event.peer -> data = "Client information";

            break;

        case ENET_EVENT_TYPE_RECEIVE:
            printf ("A packet of length %u containing %s was received from %s on channel %u.\n",
                    event.packet -> dataLength,
                    event.packet -> data,
                    event.peer -> data,
                    event.channelID);

            /* Clean up the packet now that we're done using it. */
            enet_packet_destroy (event.packet);
            
            break;
           
        case ENET_EVENT_TYPE_DISCONNECT:
            printf ("%s disconected.\n", event.peer -> data);

            /* Reset the peer's client information. */

            event.peer -> data = NULL;
        }
    }
    ...
    ...
    ...

* Sending a packet to an ENet peer            

    Packets in ENet are created with enet_packet_create(), where the size of
the packet must be specified. Optionally, initial data may be specified to 
copy into the packet.

    Certain flags may also be supplied to enet_packet_create() to control 
various packet features:

ENET_PACKET_FLAG_RELIABLE specifies that the packet must use reliable delivery.
A reliable packet is guarenteed to be delivered, and a number of retry attempts
will be made until an acknowledgement is received from the foreign host the
packet is sent to. If a certain number of retry attempts is reached without
any acknowledgement, ENet will assume the peer has disconnected and forcefully
reset the connection. If this flag is not specified, the packet is assumed
an unreliable packet, and no retry attempts will be made nor acknowledgements
generated.

    A packet may be resized (extended or truncated) with enet_packet_resize().

    A packet is sent to a foreign host with enet_peer_send(). enet_peer_send()
accepts a channel id over which to send the packet to a given peer. Once the
packet is handed over to ENet with enet_peer_send(), ENet will handle its
deallocation and enet_packet_destroy() should not be used upon it.

    One may also use enet_host_broadcast() to send a packet to all connected
peers on a given host over a specified channel id, as with enet_peer_send().

    Queued packets will be sent on a call to enet_host_service().
Alternatively, enet_host_flush() will send out queued packets without
dispatching any events.

i.e.

    /* Create a reliable packet of size 7 containing "packet\0" */
    ENetPacket * packet = enet_packet_create ("packet", 
                                              strlen ("packet") + 1, 
                                              ENET_PACKET_FLAG_RELIABLE);

    /* Extend the packet so and append the string "foo", so it now
     * contains "packetfoo\0"
     *
    enet_packet_resize (packet, strlen ("packetfoo") + 1);
    strcpy (& packet -> data [strlen ("packet")], "foo");
    
    /* Send the packet to the peer over channel id 3.
     * One could also broadcast the packet by
     * enet_host_broadcast (host, 3, packet);
     */
    enet_peer_send (peer, 3, packet);
    ...
    ...
    ...
    /* One could just use enet_host_service() instead. */
    enet_host_flush (host);

* Disconnecting an ENet peer

    Peers may be gently disconnected with enet_peer_disconnect(). A disconnect
request will be sent to the foreign host, and ENet will wait for an 
acknowledgement from the foreign host before finally disconnecting. An
event of type ENET_EVENT_TYPE_DISCONNECT will be generated once the
disconnection succeeds. Normally timeouts apply to the disconnect
acknowledgement, and so if no acknowledgement is received after a length
of time the peer will be forcefully disconnected.

    enet_peer_reset() will forcefully disconnect a peer. The foreign host
will get no notification of a disconnect and will time out on the foreign
host. No event is generated.

i.e.
    ENetEvent event;
    
    enet_peer_disconnect (& client -> peers [0]);

    /* Allow up to 3 seconds for the disconnect to succeed
     * and drop any packets received packets.
     */
    while (enet_host_service (client, & event, 3000) > 0)
    {
        switch (event.type)
        {
        case ENET_EVENT_TYPE_RECEIVE:
            enet_packet_destroy (event.packet);
            break;

        case ENET_EVENT_TYPE_DISCONNECT:
            puts ("Disconnection succeeded.");
            return;
        ...
        ...
        ...
        }
    }
    
    /* We've arrived here, so the disconnect attempt didn't succeed yet.
     * Force the connection down.
     */
    enet_peer_reset (& client -> peers [0]);
    ...
    ...
    ...

* Connecting to an ENet host

    A connection to a foregin host is initiated with enet_host_connect().
It accepts the address of a foreign host to connect to, and the number of
channels that should be allocated for communication. If N channels are
allocated for use, their channel ids will be numbered 0 through N-1.
A peer representing the connection attempt is returned, or NULL if there
were no available peers over which to initiate the connection. When the 
connection attempt succeeds, an event of type ENET_EVENT_TYPE_CONNECT will 
be generated. If the connection attempt times out or otherwise fails, an
event of type ENET_EVENT_TYPE_DISCONNECT will be generated.

i.e.
    ENetAddress address;
    ENetEvent event;
    ENetPeer *peer;

    /* Connect to some.server.net:1234. */
    enet_address_set_host (& address, "some.server.net");
    address.port = 1234;

    /* Initiate the connection, allocating the two channels 0 and 1. */
    peer = enet_host_connect (client, & address, 2);    
    
    if (peer == NULL)
    {
       fprintf (stderr, 
                "No available peers for initiating an ENet connection.\n");
       exit (EXIT_FAILURE);
    }
    
    /* Wait up to 5 seconds for the connection attempt to succeed.
    if (enet_host_service (client, & event, 5000) > 0 &&
        event.type == ENET_EVENT_TYPE_CONNECT)
    {
        puts ("Connection to some.server.net:1234 succeeded.");
        ...
        ...
        ...
    }
    else
    {
        /* Either the 5 seconds are up or a disconnect event was
         * received. Reset the peer in the event the 5 seconds
         * had run out without any significant event.
         */
        enet_peer_reset (peer);

        puts ("Connection to some.server.net:1234 failed.");
    }
    ...
    ...
    ...


--- enet.txt DELETED ---