一 服务器
#include <iostream>
#include <enet/enet.h>
using namespace std;
void main()
{
//初始化enet库
if(enet_initialize())
{
}
//下面创建服务器
ENetAddress address;
address.host=ENET_HOST_ANY;
address.port=1234;
ENetHost *server;
server=enet_host_create(&address, //主机地址
if(server==NULL)
{
}
//下面开始收数据等
ENetEvent event;
while(enet_host_service(server,&event,5000)>=0)
{
}
enet_deinitialize();
}
二 客户端
#include <iostream>
#include <enet/enet.h>
using namespace std;
void main()
{
//初始化enet库
if(enet_initialize())
{
}
//创建本地HOST对象
ENetHost *client=enet_host_create(NULL,
if(client==NULL)
{
}
//连接到服务器
ENetAddress svraddr;
enet_address_set_host(&svraddr,"127.0.0.1");
svraddr.port=1234;
ENetPeer *server=enet_host_connect(client,&svraddr,3); //client连接到svraddr对象,共分配三个通道
if(server==NULL)
{
}
ENetEvent event;
//连接成功后必须调用enet_host_service来最终确认
if (enet_host_service (client, &event, 5000) > 0 &&
//下面开始发数据
ENetPacket *packet=enet_packet_create(NULL,78,ENET_PACKET_FLAG_RELIABLE); //创建包
strcpy((char*)packet->data,"hi,哈哈");
enet_peer_send(server,1,packet);
ENetPacket *packet1=enet_packet_create(NULL,86,ENET_PACKET_FLAG_RELIABLE); //创建包
strcpy((char*)packet1->data,"你好啊,呵呵");
enet_peer_send(server,2,packet1);
enet_host_flush (client); //必须使用这个函数或是enet_host_service来使数据发出去
//关闭连接
enet_peer_disconnect (server,0);
//等待关闭成功
while (enet_host_service (client, &event, 5000)>0)
//这里就是关闭失败,强制重置
enet_peer_reset(server);
cout <<"强制重置" <<endl;
enet_deinitialize();
}