]> git.localhorst.tv Git - blank.git/blob - src/net/ConnectionHandler.hpp
collect network bandwidth usage stats
[blank.git] / src / net / ConnectionHandler.hpp
1 #ifndef BLANK_NET_CONNECTIONHANDLER_HPP_
2 #define BLANK_NET_CONNECTIONHANDLER_HPP_
3
4 #include "Packet.hpp"
5
6 #include <SDL_net.h>
7
8
9 namespace blank {
10
11 class ConnectionHandler {
12
13 public:
14         ConnectionHandler();
15
16         /// packet loss as factor
17         float PacketLoss() const noexcept { return packet_loss; }
18         /// smooth average round trip time in milliseconds
19         float RoundTripTime() const noexcept { return rtt; }
20         /// estimated kilobytes transferred per second
21         float Upstream() const noexcept { return tx_kbps; }
22         /// estimated kilobytes received per second
23         float Downstream() const noexcept { return rx_kbps; }
24
25         void PacketSent(std::uint16_t) noexcept;
26         void PacketLost(std::uint16_t);
27         void PacketReceived(std::uint16_t);
28
29         void PacketIn(const UDPpacket &) noexcept;
30         void PacketOut(const UDPpacket &) noexcept;
31
32         void Handle(const UDPpacket &);
33
34         virtual void OnTimeout() { }
35
36 private:
37         void UpdatePacketLoss() noexcept;
38         void UpdateRTT(std::uint16_t) noexcept;
39         bool SamplePacket(std::uint16_t) const noexcept;
40         int HeadDiff(std::uint16_t) const noexcept;
41         void UpdateStats() noexcept;
42
43         // called as soon as the remote end ack'd given packet
44         virtual void OnPacketReceived(std::uint16_t) { }
45         // called if the remote end probably didn't get given packet
46         virtual void OnPacketLost(std::uint16_t) { }
47
48         virtual void On(const Packet::Ping &) { }
49         virtual void On(const Packet::Login &) { }
50         virtual void On(const Packet::Join &) { }
51         virtual void On(const Packet::Part &) { }
52         virtual void On(const Packet::PlayerUpdate &) { }
53         virtual void On(const Packet::SpawnEntity &) { }
54         virtual void On(const Packet::DespawnEntity &) { }
55         virtual void On(const Packet::EntityUpdate &) { }
56         virtual void On(const Packet::PlayerCorrection &) { }
57         virtual void On(const Packet::ChunkBegin &) { }
58         virtual void On(const Packet::ChunkData &) { }
59         virtual void On(const Packet::BlockUpdate &) { }
60         virtual void On(const Packet::Message &) { }
61
62 private:
63         unsigned int packets_lost;
64         unsigned int packets_received;
65         float packet_loss;
66
67         Uint32 stamps[16];
68         std::size_t stamp_cursor;
69         std::uint16_t stamp_last;
70         float rtt;
71
72         Uint32 next_sample;
73         std::size_t tx_bytes;
74         std::size_t rx_bytes;
75         float tx_kbps;
76         float rx_kbps;
77
78 };
79
80 }
81
82 #endif