[ENet-discuss] help needed for a client/server example

Ruud van Gaal ruud at racer.nl
Thu Jan 14 05:12:30 PST 2010


...
> i'm experimenting with the Enet-Library ... so i tried to 
> write a simple client - server test application.
...
>  Now, how can i send data between server and client, after 
> the client is connected or how does the server know that a 
> client connected?
> 
> Server:
> if (enet_initialize () != 0)
...
>         server = enet_host_create (&address /* the address to 
...
>         enet_host_destroy(server);

Don't destroy the server immediately but use the same enet_host_service() to
keep the server rolling.


> PS: maybe it would be a idea to insert a full server - client 
> - example onto the homepage.

Here's something I made when I started with enet (most of it is copy/paste
from the tutorial). It uses qdbg(), which you can replace with printf() and
it probably should get you far. It actually sends packets. You should make
your QTimer type class or use something else to do your timing.

--- client.cpp ---
/*
 * enet server
 * Testing ENet for possible use in NLib
 */

#include <enet/enet.h>
#include <conio.h>
#include <qlib/debug.h>		// qdbg()

#define PORT  7000

int main(int argc,char **argv)
{
  qdbg("ENet client\n");

  if(enet_initialize () != 0)
  {
    fprintf (stderr, "An error occurred while initializing ENet.\n");
    return EXIT_FAILURE;
  }

  cstring serverName="192.168.0.72";
  qdbg("Connecting to server (%s:%d)\n",serverName,PORT);

  // Create client
  ENetHost * client;

  client = 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)
  {
      fprintf (stderr, 
               "An error occurred while trying to create an ENet client
host.\n");
      exit (EXIT_FAILURE);
  }

  ENetEvent event;
  QTimer tmr;

  // Connect to server
  ENetAddress address;
  ENetPeer *peer;

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

  /* Initiate the connection, allocating the two channels 0 and 1. */
  peer = enet_host_connect (client, & address, 2);    
  
  if(!peer)
  {
     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)
  {
      qdbg("Connection to 127.0.0.1:%d succeeded.",PORT);
  } 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);

    qerr("Connection to server failed.");
    exit(0);
  }

  // Send packets now & then
  tmr.Restart();
  while(1)
  {
    // Break?
    if(kbhit()&&getch()==27)break;

    //qdbg("Stats: 
    if(tmr.GetMilliSeconds()>1000)
    {
      // Send something
      qdbg("Send packet\n");
      ENetPacket * packet = enet_packet_create ("packet",
7,ENET_PACKET_FLAG_RELIABLE);

      /* Send the packet to the peer over channel id 0. */
      /* One could also broadcast the packet by         */
      /* enet_host_broadcast (host, 0, packet);         */
      enet_peer_send (peer, 0, packet);

      tmr.Restart();
    }

    if(enet_host_service (client, & event, 0) > 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;
        }
    }
  }

  // Disconnect
  enet_peer_disconnect(peer,0);

  // Allow up to 3 seconds for the disconnect to succeed and drop any
packets received packets.
  bool ok=false;
  if(enet_host_service (client, & event, 3000) > 0)
  {
    switch (event.type)
    {
      case ENET_EVENT_TYPE_RECEIVE:
        qdbg("Drop packet while disconnecting.\n");
        enet_packet_destroy (event.packet);
        break;

      case ENET_EVENT_TYPE_DISCONNECT:
        qdbg("Disconnect succeeded.\n");
        ok=true;
        break;
    }
  }

  if(!ok)
  {
    /* We've arrived here, so the disconnect attempt didn't */
    /* succeed yet.  Force the connection down.             */
    qdbg("Disconnect failed.\n");
    enet_peer_reset (peer);
  }

  // Cleanup
  //enet_host_destroy(client);
  enet_deinitialize();

  return 0;
}

--- server.cpp ---
/*
 * enet server
 * Testing ENet for possible use in NLib
 */

#include <enet/enet.h>
#include <conio.h>
#include <qlib/debug.h>		// printf (try stdio.h instead)

#define PORT  7000

int main(int argc,char **argv)
{
  qdbg("ENet server\n");

  if(enet_initialize () != 0)
  {
    fprintf (stderr, "An error occurred while initializing ENet.\n");
    return EXIT_FAILURE;
  }

  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 = PORT;

  printf("Creating server on %s:%d\n",address.host,address.port);

  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)
  {
      fprintf (stderr, 
               "An error occurred while trying to create an ENet server
host.\n");
      exit (EXIT_FAILURE);
  }

  // Listen
  qdbg("Listening. Press ESC to quit.\n");

   ENetEvent event;
    
    while (1)
    {
      if(enet_host_service (server, & event, 100) > 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;
        }
      }

      if(kbhit()&&getch()==27)break;
    }

  // Cleanup
  enet_host_destroy(server);
  enet_deinitialize();

  return 0;
}



More information about the ENet-discuss mailing list