00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #include "net/tmwserv/connection.h"
00023
00024 #include "net/tmwserv/internal.h"
00025
00026 #include "net/messageout.h"
00027
00028 #include "log.h"
00029
00030 #include <string>
00031
00032 Net::Connection::Connection(ENetHost *client):
00033 mConnection(0), mClient(client)
00034 {
00035 Net::connections++;
00036 }
00037
00038 Net::Connection::~Connection()
00039 {
00040 Net::connections--;
00041 }
00042
00043 bool Net::Connection::connect(const std::string &address, short port)
00044 {
00045 logger->log("Net::Connection::connect(%s, %i)", address.c_str(), port);
00046
00047 if (address.empty())
00048 {
00049 logger->log("Net::Connection::connect() got empty address!");
00050 mState = NET_ERROR;
00051 return false;
00052 }
00053
00054 ENetAddress enetAddress;
00055
00056 enet_address_set_host(&enetAddress, address.c_str());
00057 enetAddress.port = port;
00058
00059
00060 mConnection = enet_host_connect(mClient, &enetAddress, 1);
00061
00062 if (!mConnection)
00063 {
00064 logger->log("Unable to initiate connection to the server.");
00065 mState = NET_ERROR;
00066 return false;
00067 }
00068
00069 return true;
00070 }
00071
00072 void Net::Connection::disconnect()
00073 {
00074 if (!mConnection)
00075 return;
00076
00077 enet_peer_disconnect(mConnection, 0);
00078 enet_host_flush(mClient);
00079 enet_peer_reset(mConnection);
00080
00081 mConnection = 0;
00082 }
00083
00084 bool Net::Connection::isConnected()
00085 {
00086 return (mConnection) ?
00087 (mConnection->state == ENET_PEER_STATE_CONNECTED) : false;
00088 }
00089
00090 void Net::Connection::send(const MessageOut &msg)
00091 {
00092 if (!isConnected())
00093 {
00094 logger->log("Warning: cannot send message to not connected server!");
00095 return;
00096 }
00097
00098
00099
00100 ENetPacket *packet = enet_packet_create(msg.getData(),
00101 msg.getDataSize(),
00102 ENET_PACKET_FLAG_RELIABLE);
00103 enet_peer_send(mConnection, 0, packet);
00104 }