00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #include "net/connection.hpp"
00023 #include "net/bandwidth.hpp"
00024 #include "net/messagein.hpp"
00025 #include "net/messageout.hpp"
00026 #include "utils/logger.h"
00027
00028 Connection::Connection():
00029 mRemote(0),
00030 mLocal(0)
00031 {
00032 }
00033
00034 bool Connection::start(const std::string &address, int port)
00035 {
00036 ENetAddress enetAddress;
00037 enet_address_set_host(&enetAddress, address.c_str());
00038 enetAddress.port = port;
00039
00040 mLocal = enet_host_create(NULL ,
00041 1 ,
00042 0 ,
00043 0 );
00044
00045 if (!mLocal)
00046 return false;
00047
00048
00049 mRemote = enet_host_connect(mLocal, &enetAddress, 1);
00050
00051 ENetEvent event;
00052 if (enet_host_service(mLocal, &event, 10000) <= 0 ||
00053 event.type != ENET_EVENT_TYPE_CONNECT)
00054 {
00055 stop();
00056 return false;
00057 }
00058 return mRemote;
00059 }
00060
00061 void Connection::stop()
00062 {
00063 if (mRemote)
00064 enet_peer_disconnect(mRemote, 0);
00065 if (mLocal)
00066 enet_host_flush(mLocal);
00067 if (mRemote)
00068 enet_peer_reset(mRemote);
00069 if (mLocal)
00070 enet_host_destroy(mLocal);
00071
00072 mRemote = 0;
00073 mLocal = 0;
00074 }
00075
00076 bool Connection::isConnected() const
00077 {
00078 return mRemote && mRemote->state == ENET_PEER_STATE_CONNECTED;
00079 }
00080
00081 void Connection::send(const MessageOut &msg, bool reliable, unsigned channel)
00082 {
00083 if (!mRemote) {
00084 LOG_WARN("Can't send message to unconnected host! (" << msg << ")");
00085 return;
00086 }
00087
00088 gBandwidth->increaseInterServerOutput(msg.getLength());
00089
00090 ENetPacket *packet;
00091 packet = enet_packet_create(msg.getData(),
00092 msg.getLength(),
00093 reliable ? ENET_PACKET_FLAG_RELIABLE : 0);
00094
00095 if (packet)
00096 enet_peer_send(mRemote, channel, packet);
00097 else
00098 LOG_ERROR("Failure to create packet!");
00099 }
00100
00101 void Connection::process()
00102 {
00103 ENetEvent event;
00104
00105 while (enet_host_service(mLocal, &event, 0) > 0)
00106 {
00107 switch (event.type)
00108 {
00109 case ENET_EVENT_TYPE_RECEIVE:
00110 if (event.packet->dataLength >= 2)
00111 {
00112 MessageIn msg((char *)event.packet->data,
00113 event.packet->dataLength);
00114 gBandwidth->increaseInterServerInput(event.packet->dataLength);
00115 processMessage(msg);
00116 }
00117 else
00118 {
00119 LOG_WARN("Message too short.");
00120 }
00121
00122 enet_packet_destroy(event.packet);
00123 break;
00124
00125 default:
00126 break;
00127 }
00128 }
00129 }