nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
connection.cc
Go to the documentation of this file.
1#include "client/connection.h"
2
3#include <chrono>
4#include <cstddef>
5#include <memory>
6#include <string>
7#include <utility>
8#include <vector>
9
10#include "absl/memory/memory.h"
11#include "absl/strings/str_cat.h"
12#include "asio/buffer.hpp"
13#include "asio/connect.hpp"
14#include "asio/ssl/stream_base.hpp"
15#include "asio/write.hpp"
16
17namespace nanommo {
18
19absl::StatusOr<std::unique_ptr<Connection>> Connection::Create(
20 const std::string& host, uint16_t port, asio::ssl::context& tls,
21 const std::string& token, bool udp) {
22 std::unique_ptr<Connection> connection =
23 absl::WrapUnique(new Connection(tls, token));
24 const absl::Status started = connection->Start(host, port, token, udp);
25 if (!started.ok()) {
26 return started;
27 }
28 return connection;
29}
30
31Connection::Connection(asio::ssl::context& tls, const std::string& token)
32 : stream_(io_, tls), udp_socket_(io_), hello_timer_(io_), token_(token) {}
33
34absl::Status Connection::Start(const std::string& host, uint16_t port,
35 const std::string& token, bool udp) {
36 asio::ip::tcp::resolver resolver(io_);
37 std::error_code error;
38 // IPv4, which the servers listen on, as LogIn looks up.
39 const asio::ip::tcp::resolver::results_type endpoints =
40 resolver.resolve(asio::ip::tcp::v4(), host, std::to_string(port), error);
41 if (!error) {
42 asio::connect(stream_.lowest_layer(), endpoints, error);
43 }
44 if (error) {
45 return absl::UnavailableError(absl::StrCat(
46 "couldn't connect to ", host, ":", port, ": ", error.message()));
47 }
48 std::error_code ignored;
49 stream_.lowest_layer().set_option(asio::ip::tcp::no_delay(true), ignored);
50 ExpectName(stream_, host);
51 stream_.handshake(asio::ssl::stream_base::client, error);
52 if (error) {
53 return absl::UnavailableError(
54 absl::StrCat("couldn't shake hands with the world: ",
55 HandshakeError(stream_, host, error)));
56 }
57 protocol::Hello hello;
58 hello.set_token(token);
59 asio::write(stream_, asio::buffer(Frame(hello)), error);
60 if (error) {
61 return absl::UnavailableError(
62 absl::StrCat("couldn't say hello to the server: ", error.message()));
63 }
64 Read();
65 if (udp) {
66 const asio::ip::tcp::endpoint server =
67 stream_.lowest_layer().remote_endpoint(error);
68 if (!error) {
69 udp_socket_.connect({server.address(), server.port()}, error);
70 }
71 if (error) {
72 return absl::UnavailableError(absl::StrCat(
73 "couldn't reach the server over UDP: ", error.message()));
74 }
75 HelloOverUdp();
76 ReceiveOverUdp();
77 }
78 return absl::OkStatus();
79}
80
81void Connection::Poll() { io_.poll(); }
82
83void Connection::Send(const protocol::Input& input) {
84 if (!connected_) {
85 return;
86 }
87 std::error_code error;
88 asio::write(stream_, asio::buffer(Frame(input)), error);
89 if (error) {
90 connected_ = false;
91 }
92}
93
94void Connection::Read() {
95 stream_.async_read_some(asio::buffer(buffer_),
96 [this](std::error_code error, std::size_t size) {
97 if (error) {
98 connected_ = false;
99 return;
100 }
101 reader_.Append({buffer_.data(), size});
102 while (const auto message = reader_.Next()) {
103 if (!inbox_.Take(*message).ok()) {
104 connected_ = false;
105 return;
106 }
107 }
108 if (!reader_.status().ok()) {
109 connected_ = false;
110 return;
111 }
112 Read();
113 });
114}
115
116void Connection::HelloOverUdp() {
117 if (udp_worlds_) {
118 return;
119 }
120 protocol::Hello hello;
121 hello.set_token(token_);
122 std::error_code ignored;
123 udp_socket_.send(asio::buffer(hello.SerializeAsString()), 0, ignored);
124 hello_timer_.expires_after(std::chrono::milliseconds(250));
125 hello_timer_.async_wait([this](std::error_code error) {
126 if (!error) {
127 HelloOverUdp();
128 }
129 });
130}
131
132void Connection::ReceiveOverUdp() {
133 udp_socket_.async_receive(
134 asio::buffer(datagram_), [this](std::error_code error, std::size_t size) {
135 protocol::World part;
136 if (!error &&
137 part.ParseFromArray(datagram_.data(), static_cast<int>(size))) {
138 udp_worlds_ = true;
139 inbox_.Add(part);
140 }
141 ReceiveOverUdp();
142 });
143}
144
145} // namespace nanommo
Connection(const Connection &)=delete
void Poll() override
Takes in what's arrived, without waiting.
Definition connection.cc:81
static absl::StatusOr< std::unique_ptr< Connection > > Create(const std::string &host, uint16_t port, asio::ssl::context &tls, const std::string &token, bool udp)
Connects to the server over TLS, or returns why it couldn't.
Definition connection.cc:19
void Send(const protocol::Input &input) override
Definition connection.cc:83
void Append(std::string_view bytes)
Definition framing.cc:19
Definition chat.cc:9
std::string HandshakeError(TlsStream &stream, const std::string &host, const std::error_code &error)
Why a client's handshake with host failed, and what to do about it.
Definition tls.cc:64
std::string Frame(const google::protobuf::MessageLite &message)
The size goes in front, as four bytes in network byte order.
Definition framing.cc:14
void ExpectName(TlsStream &stream, const std::string &host)
Definition tls.cc:52