사용자 도구

사이트 도구


kb:enet

ENet

  • 안정적인 전송을 제공하는 UDP 네트워크 라이브러리.
  • Cube라는 오픈소스 FPS 게임에서 파생되었다.
  • 상당히 작고(헤더,소스 모두 합쳐 110KB 정도) 쓰기 쉽다.

서버 샘플

#include <enet/enet.h>
#pragma comment(lib, "enet_debug")
 
int main()
{
    enet_initialize();
 
    ENetAddress address;
    ENetHost* server = NULL;
 
    address.host = ENET_HOST_ANY;
    address.port = 1234;
 
    server = enet_host_create(&address, 32, 0, 0);
    if (server == NULL)
    {
        fprintf(stderr, "An error occurred while trying to create an ENet server host.\n");
        enet_deinitialize();
        return 0;
    }
 
    while (true)
    {
        ENetEvent event;
        while (enet_host_service(server, & event, 1) > 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);
                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);
                enet_packet_destroy (event.packet);
                break;
            case ENET_EVENT_TYPE_DISCONNECT:
                printf("%s disconected.\n", event.peer->data);
                event.peer->data = NULL;
            }
        }
    }
 
    enet_host_destroy(server);
 
    enet_deinitialize();
    return 0;
}

클라이언트 샘플

#include <enet/enet.h>
#pragma comment(lib, "enet_debug")
 
int main()
{
    enet_initialize();
 
    ENetHost* client = enet_host_create(NULL, 1, 0, 0);
    if (client == NULL)
    {
        fprintf(stderr, 
            "An error occurred while trying to create an ENet client host.\n");
        exit(EXIT_FAILURE);
    }
 
    ENetAddress address;
    enet_address_set_host(&address, "localhost");
    address.port = 1234;
 
    ENetPeer* peer = enet_host_connect(client, &address, 2);
    if (peer == NULL)
    {
        fprintf(stderr, "No available peers for initiating an ENet connection.\n");
        exit(EXIT_FAILURE);
    }
 
    ENetEvent event;
    if (enet_host_service (client, & event, 5000) > 0 &&
        event.type == ENET_EVENT_TYPE_CONNECT)
    {
        printf("Connection to some.server.net:1234 succeeded.");
 
        for (int i=0; i<5; ++i)
        {
            ENetPacket * packet = enet_packet_create(
                "packet", strlen("packet") + 1, ENET_PACKET_FLAG_RELIABLE);
 
            enet_peer_send(peer, 0, packet);
 
            enet_host_flush(client);
        }
    }
    else
    {
        printf("Connection failed.");
    }
 
    enet_host_destroy(client);
    enet_deinitialize();
 
    return 0;
}
kb/enet.txt · 마지막으로 수정됨: 2014/11/07 20:31 (바깥 편집)