Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/external/enet/docs/tutorial.dox @ 7498

Last change on this file since 7498 was 7459, checked in by adrfried, 14 years ago

Merged ipv6 branch

Orxonox now includes a modified version of ENet 1.3.0

  • Property svn:eol-style set to native
File size: 12.0 KB
RevLine 
[7328]1/**
2@page Tutorial Tutorial
3
4@ref Initialization
5
6@ref CreateServer
7
8@ref CreateClient
9
10@ref ManageHost
11
12@ref SendingPacket
13
14@ref Disconnecting
15
16@ref Connecting
17
18@section Initialization Initialization
19
20You should include the file <enet/enet.h> when using ENet. Do not
21include <enet.h> without the directory prefix, as this may cause
22file name conflicts on some systems.
23
24Before using ENet, you must call enet_initialize() to initialize the
25library. Upon program exit, you should call enet_deinitialize() so
26that the library may clean up any used resources.
27
28@code
29#include <enet/enet.h>
30
31int
32main (int argc, char ** argv)
33{
34    if (enet_initialize () != 0)
35    {
36        fprintf (stderr, "An error occurred while initializing ENet.\n");
37        return EXIT_FAILURE;
38    }
39    atexit (enet_deinitialize);
40    ...
41    ...
42    ...
43}
44@endcode
45       
46@section CreateServer Creating an ENet server
47
48Servers in ENet are constructed with enet_host_create(). You must
49specify an address on which to receive data and new connections, as
50well as the maximum allowable numbers of connected peers. You may
51optionally specify the incoming and outgoing bandwidth of the server
52in bytes per second so that ENet may try to statically manage
53bandwidth resources among connected peers in addition to its dynamic
54throttling algorithm; specifying 0 for these two options will cause
55ENet to rely entirely upon its dynamic throttling algorithm to manage
56bandwidth.
57
58When done with a host, the host may be destroyed with
59enet_host_destroy().  All connected peers to the host will be reset,
60and the resources used by the host will be freed.
61
62@code
63    ENetAddress address;
64    ENetHost * server;
65
66    /* Bind the server to the default localhost.     */
67    /* A specific host address can be specified by   */
68    /* enet_address_set_host (& address, "x.x.x.x"); */
69
70    address.host = ENET_HOST_ANY;
71    /* Bind the server to port 1234. */
72    address.port = 1234;
73
74    server = enet_host_create (& address /* the address to bind the server host to */,
75                                 32      /* allow up to 32 clients and/or outgoing connections */,
76                                  2      /* allow up to 2 channels to be used, 0 and 1 */,
77                                  0      /* assume any amount of incoming bandwidth */,
78                                  0      /* assume any amount of outgoing bandwidth */);
79    if (server == NULL)
80    {
81        fprintf (stderr,
82                 "An error occurred while trying to create an ENet server host.\n");
83        exit (EXIT_FAILURE);
84    }
85    ...
86    ...
87    ...
88    enet_host_destroy(server);
89@endcode
90
91@section CreateClient Creating an ENet client
92
93Clients in ENet are similarly constructed with enet_host_create() when
94no address is specified to bind the host to. Bandwidth may be
95specified for the client host as in the above example. The peer count
96controls the maximum number of connections to other server hosts that
97may be simultaneously open.
98
99@code
100    ENetHost * client;
101
102    client = enet_host_create (NULL /* create a client host */,
103                1 /* only allow 1 outgoing connection */,
104                2 /* allow up 2 channels to be used, 0 and 1 */,
105                57600 / 8 /* 56K modem with 56 Kbps downstream bandwidth */,
106                14400 / 8 /* 56K modem with 14 Kbps upstream bandwidth */);
107
108    if (client == NULL)
109    {
110        fprintf (stderr,
111                 "An error occurred while trying to create an ENet client host.\n");
112        exit (EXIT_FAILURE);
113    }
114    ...
115    ...
116    ...
117    enet_host_destroy(client);
118@endcode
119
120@section ManageHost Managing an ENet host
121
122ENet uses a polled event model to notify the programmer of significant
123events. ENet hosts are polled for events with enet_host_service(),
124where an optional timeout value in milliseconds may be specified to
125control how long ENet will poll; if a timeout of 0 is specified,
126enet_host_service() will return immediately if there are no events to
127dispatch. enet_host_service() will return 1 if an event was dispatched
128within the specified timeout.
129
130Currently there are only four types of significant events in ENet:
131
132An event of type ENET_EVENT_TYPE_NONE is returned if no event occurred
133within the specified time limit. enet_host_service() will return 0
134with this event.
135
136An event of type ENET_EVENT_TYPE_CONNECT is returned when either a new client
137host has connected to the server host or when an attempt to establish a
138connection with a foreign host has succeeded. Only the "peer" field of the
139event structure is valid for this event and contains the newly connected peer.
140
141An event of type ENET_EVENT_TYPE_RECEIVE is returned when a packet is received
142from a connected peer. The "peer" field contains the peer the packet was
143received from, "channelID" is the channel on which the packet was sent, and
144"packet" is the packet that was sent. The packet contained in the "packet"
145field must be destroyed with enet_packet_destroy() when you are done
146inspecting its contents.
147
148An event of type ENET_EVENT_TYPE_DISCONNECT is returned when a connected peer
149has either explicitly disconnected or timed out. Only the "peer" field of the
150event structure is valid for this event and contains the peer that
151disconnected. Only the "data" field of the peer is still valid on a
152disconnect event and must be explicitly reset.
153
154@code
155    ENetEvent event;
156   
157    /* Wait up to 1000 milliseconds for an event. */
158    while (enet_host_service (client, & event, 1000) > 0)
159    {
160        switch (event.type)
161        {
162        case ENET_EVENT_TYPE_CONNECT:
163            printf ("A new client connected from %x:%u.\n",
164                    event.peer -> address.host,
165                    event.peer -> address.port);
166
167            /* Store any relevant client information here. */
168            event.peer -> data = "Client information";
169
170            break;
171
172        case ENET_EVENT_TYPE_RECEIVE:
173            printf ("A packet of length %u containing %s was received from %s on channel %u.\n",
174                    event.packet -> dataLength,
175                    event.packet -> data,
176                    event.peer -> data,
177                    event.channelID);
178
179            /* Clean up the packet now that we're done using it. */
180            enet_packet_destroy (event.packet);
181           
182            break;
183           
184        case ENET_EVENT_TYPE_DISCONNECT:
185            printf ("%s disconected.\n", event.peer -> data);
186
187            /* Reset the peer's client information. */
188
189            event.peer -> data = NULL;
190        }
191    }
192    ...
193    ...
194    ...
195@endcode
196
197@section SendingPacket Sending a packet to an ENet peer           
198
199Packets in ENet are created with enet_packet_create(), where the size
200of the packet must be specified. Optionally, initial data may be
201specified to copy into the packet.
202
203Certain flags may also be supplied to enet_packet_create() to control
204various packet features:
205
206ENET_PACKET_FLAG_RELIABLE specifies that the packet must use reliable
207delivery.  A reliable packet is guarenteed to be delivered, and a
208number of retry attempts will be made until an acknowledgement is
209received from the foreign host the packet is sent to. If a certain
210number of retry attempts is reached without any acknowledgement, ENet
211will assume the peer has disconnected and forcefully reset the
212connection. If this flag is not specified, the packet is assumed an
213unreliable packet, and no retry attempts will be made nor
214acknowledgements generated.
215
216A packet may be resized (extended or truncated) with
217enet_packet_resize().
218
219A packet is sent to a foreign host with
220enet_peer_send(). enet_peer_send() accepts a channel id over which to
221send the packet to a given peer. Once the packet is handed over to
222ENet with enet_peer_send(), ENet will handle its deallocation and
223enet_packet_destroy() should not be used upon it.
224
225One may also use enet_host_broadcast() to send a packet to all
226connected peers on a given host over a specified channel id, as with
227enet_peer_send().
228
229Queued packets will be sent on a call to enet_host_service().
230Alternatively, enet_host_flush() will send out queued packets without
231dispatching any events.
232
233@code
234    /* Create a reliable packet of size 7 containing "packet\0" */
235    ENetPacket * packet = enet_packet_create ("packet",
236                                              strlen ("packet") + 1,
237                                              ENET_PACKET_FLAG_RELIABLE);
238
239    /* Extend the packet so and append the string "foo", so it now */
240    /* contains "packetfoo\0"                                      */
241    enet_packet_resize (packet, strlen ("packetfoo") + 1);
242    strcpy (& packet -> data [strlen ("packet")], "foo");
243   
244    /* Send the packet to the peer over channel id 0. */
245    /* One could also broadcast the packet by         */
246    /* enet_host_broadcast (host, 0, packet);         */
247    enet_peer_send (peer, 0, packet);
248    ...
249    ...
250    ...
251    /* One could just use enet_host_service() instead. */
252    enet_host_flush (host);
253@endcode
254
255@section Disconnecting Disconnecting an ENet peer
256
257Peers may be gently disconnected with enet_peer_disconnect(). A
258disconnect request will be sent to the foreign host, and ENet will
259wait for an acknowledgement from the foreign host before finally
260disconnecting. An event of type ENET_EVENT_TYPE_DISCONNECT will be
261generated once the disconnection succeeds. Normally timeouts apply to
262the disconnect acknowledgement, and so if no acknowledgement is
263received after a length of time the peer will be forcefully
264disconnected.
265
266enet_peer_reset() will forcefully disconnect a peer. The foreign host
267will get no notification of a disconnect and will time out on the
268foreign host. No event is generated.
269
270@code
271    ENetEvent event;
272   
273    enet_peer_disconnect (peer, 0);
274
275    /* Allow up to 3 seconds for the disconnect to succeed
276     * and drop any packets received packets.
277     */
278    while (enet_host_service (client, & event, 3000) > 0)
279    {
280        switch (event.type)
281        {
282        case ENET_EVENT_TYPE_RECEIVE:
283            enet_packet_destroy (event.packet);
284            break;
285
286        case ENET_EVENT_TYPE_DISCONNECT:
287            puts ("Disconnection succeeded.");
288            return;
289        ...
290        ...
291        ...
292        }
293    }
294   
295    /* We've arrived here, so the disconnect attempt didn't */
296    /* succeed yet.  Force the connection down.             */
297    enet_peer_reset (peer);
298    ...
299    ...
300    ...
301@endcode
302
303@section Connecting Connecting to an ENet host
304
305A connection to a foreign host is initiated with enet_host_connect().
306It accepts the address of a foreign host to connect to, and the number
307of channels that should be allocated for communication. If N channels
308are allocated for use, their channel ids will be numbered 0 through
309N-1.  A peer representing the connection attempt is returned, or NULL
310if there were no available peers over which to initiate the
311connection. When the connection attempt succeeds, an event of type
312ENET_EVENT_TYPE_CONNECT will be generated. If the connection attempt
313times out or otherwise fails, an event of type
314ENET_EVENT_TYPE_DISCONNECT will be generated.
315
316@code
317    ENetAddress address;
318    ENetEvent event;
319    ENetPeer *peer;
320
321    /* Connect to some.server.net:1234. */
322    enet_address_set_host (& address, "some.server.net");
323    address.port = 1234;
324
325    /* Initiate the connection, allocating the two channels 0 and 1. */
326    peer = enet_host_connect (client, & address, 2, 0);   
327   
328    if (peer == NULL)
329    {
330       fprintf (stderr,
331                "No available peers for initiating an ENet connection.\n");
332       exit (EXIT_FAILURE);
333    }
334   
335    /* Wait up to 5 seconds for the connection attempt to succeed. */
336    if (enet_host_service (client, & event, 5000) > 0 &&
337        event.type == ENET_EVENT_TYPE_CONNECT)
338    {
339        puts ("Connection to some.server.net:1234 succeeded.");
340        ...
341        ...
342        ...
343    }
344    else
345    {
346        /* Either the 5 seconds are up or a disconnect event was */
347        /* received. Reset the peer in the event the 5 seconds   */
348        /* had run out without any significant event.            */
349        enet_peer_reset (peer);
350
351        puts ("Connection to some.server.net:1234 failed.");
352    }
353    ...
354    ...
355    ...
356@endcode
357*/
Note: See TracBrowser for help on using the repository browser.