| 6 |
| * Copyright Nikolai Kudashov, 2015. |
| 7 | */ |
| 8 |
| 9 | #ifndef CONNECTION_H |
| 10 | #define CONNECTION_H |
| 11 |
| 12 | #include <pthread.h> |
| 13 | #include <vector> |
| 14 | #include <string> |
| 15 | #include "ConnectionSession.h" |
| 16 | #include "ConnectionSocket.h" |
| 17 | #include "Defines.h" |
| 18 |
| 19 | class Datacenter; |
| 20 | class Timer; |
| 21 | class ByteStream; |
| 22 |
| 23 | class Connection : public ConnectionSession, public ConnectionSocket { |
| 24 |
| 25 | public: |
| 26 |
| 27 | Connection(Datacenter *datacenter, ConnectionType type); |
| 28 | ~Connection(); |
| 29 |
| 30 | void connect(); |
| 31 | void suspendConnection(); |
| 32 | void sendData(NativeByteBuffer *buffer, bool reportAck); |
| 33 | uint32_t getConnectionToken(); |
| 34 | ConnectionType getConnectionType(); |
| 35 | Datacenter *getDatacenter(); |
| 36 |
| 37 | protected: |
| 38 |
| 39 | void onReceivedData(NativeByteBuffer *buffer) override; |
| 40 | void onDisconnected(int reason) override; |
| 41 | void onConnected() override; |
| 42 | void reconnect(); |
| 43 |
| 44 | private: |
| 45 |
| 46 | enum TcpConnectionState { |
| 47 | TcpConnectionStageIdle, |
| 48 | TcpConnectionStageConnecting, |
| 49 | TcpConnectionStageReconnecting, |
| 50 | TcpConnectionStageConnected, |
| 51 | TcpConnectionStageSuspended |
| 52 | }; |
| 53 |
| 54 | TcpConnectionState connectionState = TcpConnectionStageIdle; |
| 55 | uint32_t connectionToken = 0; |
| 56 | std::string hostAddress; |
| 57 | uint16_t hostPort; |
| 58 | uint16_t failedConnectionCount; |
| 59 | Datacenter *currentDatacenter; |
| 60 | uint32_t currentAddressFlags; |
| 61 | ConnectionType connectionType; |
| 62 | bool firstPacketSent = false; |
| 63 | NativeByteBuffer *restOfTheData = nullptr; |
| 64 | uint32_t lastPacketLength = 0; |
| 65 | bool hasSomeDataSinceLastConnect = false; |
| 66 | bool isTryingNextPort = false; |
| 67 | bool wasConnected = false; |
| 68 | uint32_t willRetryConnectCount = 5; |
| 69 | Timer *reconnectTimer; |
| 70 |
| 71 | friend class ConnectionsManager; |
| 72 | }; |
| 73 |
| 74 | #endif |
| 75 |