aboutsummaryrefslogtreecommitdiff
path: root/comp3331/server/src/shared/connection.hh
blob: d7237cb5b27b0db8e940751dafc1485d313a73fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#ifndef SHARED_CONNECTION_HH_
#define SHARED_CONNECTION_HH_

#include <atomic>
#include <memory>
#include <mutex>
#include <vector>

#include "shared/net.hh"

namespace shared {

// The connection class abstracts sending and receiving data, including reliable
// transmission over UDP.
class connection {
private:
    shared::socket_t sock;
    sockaddr_in info;

private:
    std::uint32_t seq_num = 0; // track packet sequence number
    std::uint32_t ack_num = 0;

    // for reliable transport, spawn a new thread which reads sent/received
    std::unique_ptr<std::atomic<bool>> should_thread_exit;
    std::unique_ptr<std::mutex> lock;
    std::vector<packet> sent;
    std::vector<packet> received;
    std::shared_ptr<std::thread> reliable_transport_thread;
    void do_reliable_transport() noexcept;

public:
    connection(const socket_t& sock, sockaddr_in&& info)
        : sock(sock), info(std::move(info)),
          should_thread_exit(std::make_unique<std::atomic<bool>>(false)),
          lock(std::make_unique<std::mutex>()),
          reliable_transport_thread(std::make_shared<std::thread>(
              &connection::do_reliable_transport, this)) {}

    connection(const connection&) = delete;
    connection(connection&&) = default;
    ~connection() noexcept {
        *this->should_thread_exit = true;
        this->reliable_transport_thread->join();
    }

public:
    const sockaddr_in& get_info() const noexcept { return this->info; }
    const socket_t& get_socket() const noexcept { return this->sock; }

public:
    // All unreliable packets should go through these functions so we may track
    // if our packets have been sent or received, making them reliable.
    void send_packet(packet&& packet) noexcept;
    bool should_discard_packet(const packet& packet) noexcept;
};

} // namespace shared

#endif