nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
websocket_link.cc
Go to the documentation of this file.
2
3#include <emscripten.h>
4#include <emscripten/websocket.h>
5
6#include <memory>
7#include <optional>
8#include <string>
9#include <string_view>
10#include <utility>
11
12#include "absl/memory/memory.h"
13#include "absl/strings/str_cat.h"
14
15namespace nanommo {
16namespace {
17
18// How long a socket has to open, and a login to be answered, in
19// milliseconds: the game waits, and the browser has the page meanwhile.
20constexpr int kOpenWait = 10000;
21constexpr int kAnswerWait = 10000;
22
23// How often a wait looks again, in milliseconds.
24constexpr int kTick = 10;
25
26} // namespace
27
28absl::StatusOr<std::unique_ptr<WebSocket>> WebSocket::Open(
29 const std::string& url) {
30 EmscriptenWebSocketCreateAttributes attributes;
31 emscripten_websocket_init_create_attributes(&attributes);
32 attributes.url = url.c_str();
33 attributes.createOnMainThread = true;
34 const EMSCRIPTEN_WEBSOCKET_T handle = emscripten_websocket_new(&attributes);
35 if (handle <= 0) {
36 return absl::UnavailableError(absl::StrCat("couldn't open ", url));
37 }
38 std::unique_ptr<WebSocket> socket = absl::WrapUnique(new WebSocket(handle));
39 emscripten_websocket_set_onopen_callback(handle, socket.get(), OnOpen);
40 emscripten_websocket_set_onmessage_callback(handle, socket.get(), OnMessage);
41 emscripten_websocket_set_onerror_callback(handle, socket.get(), OnError);
42 emscripten_websocket_set_onclose_callback(handle, socket.get(), OnClose);
43 // Asyncify lets the sleep hand the page back to the browser, which opens
44 // the socket and calls us back meanwhile.
45 for (int waited = 0;
46 !socket->opened_ && !socket->closed_ && waited < kOpenWait;
47 waited += kTick) {
48 emscripten_sleep(kTick);
49 }
50 if (!socket->open()) {
51 return absl::UnavailableError(
52 absl::StrCat("couldn't reach the gateway at ", url));
53 }
54 return socket;
55}
56
58 emscripten_websocket_close(socket_, 1000, "");
59 emscripten_websocket_delete(socket_);
60}
61
62absl::Status WebSocket::Send(std::string_view bytes) {
63 if (!open()) {
64 return absl::UnavailableError("the gateway closed the connection");
65 }
66 std::string owned(bytes);
67 if (emscripten_websocket_send_binary(socket_, owned.data(),
68 static_cast<uint32_t>(owned.size())) !=
69 EMSCRIPTEN_RESULT_SUCCESS) {
70 return absl::UnavailableError("couldn't send to the gateway");
71 }
72 return absl::OkStatus();
73}
74
75std::string WebSocket::Take() { return std::exchange(received_, {}); }
76
77void WebSocket::Wait(int milliseconds) {
78 for (int waited = 0; received_.empty() && open() && waited < milliseconds;
79 waited += kTick) {
80 emscripten_sleep(kTick);
81 }
82}
83
84bool WebSocket::OnOpen(int, const EmscriptenWebSocketOpenEvent*, void* self) {
85 static_cast<WebSocket*>(self)->opened_ = true;
86 return true;
87}
88
89bool WebSocket::OnMessage(int, const EmscriptenWebSocketMessageEvent* event,
90 void* self) {
91 static_cast<WebSocket*>(self)->received_.append(
92 reinterpret_cast<const char*>(event->data), event->numBytes);
93 return true;
94}
95
96bool WebSocket::OnError(int, const EmscriptenWebSocketErrorEvent*, void* self) {
97 static_cast<WebSocket*>(self)->closed_ = true;
98 return true;
99}
100
101bool WebSocket::OnClose(int, const EmscriptenWebSocketCloseEvent*, void* self) {
102 static_cast<WebSocket*>(self)->closed_ = true;
103 return true;
104}
105
106absl::StatusOr<protocol::LoginReply> AskOverWebSocket(
107 const std::string& url, const protocol::LoginRequest& request) {
108 absl::StatusOr<std::unique_ptr<WebSocket>> socket = WebSocket::Open(url);
109 if (!socket.ok()) {
110 return socket.status();
111 }
112 if (const absl::Status sent = (*socket)->Send(Frame(request)); !sent.ok()) {
113 return sent;
114 }
115 FrameReader reader;
116 for (int waited = 0; waited < kAnswerWait; waited += kTick) {
117 reader.Append((*socket)->Take());
118 if (const std::optional<std::string> message = reader.Next()) {
119 protocol::LoginReply reply;
120 if (!reply.ParseFromString(*message)) {
121 return absl::DataLossError("couldn't read the login server's reply");
122 }
123 return reply;
124 }
125 if (!reader.status().ok()) {
126 return reader.status();
127 }
128 if (!(*socket)->open()) {
129 return absl::UnavailableError("the gateway closed before the answer");
130 }
131 (*socket)->Wait(kTick);
132 }
133 return absl::DeadlineExceededError("the login server didn't answer");
134}
135
136absl::StatusOr<std::unique_ptr<WebSocketLink>> WebSocketLink::Open(
137 const std::string& url, const std::string& token) {
138 absl::StatusOr<std::unique_ptr<WebSocket>> socket = WebSocket::Open(url);
139 if (!socket.ok()) {
140 return socket.status();
141 }
142 protocol::Hello hello;
143 hello.set_token(token);
144 if (const absl::Status sent = (*socket)->Send(Frame(hello)); !sent.ok()) {
145 return sent;
146 }
147 return absl::WrapUnique(new WebSocketLink(*std::move(socket)));
148}
149
151 reader_.Append(socket_->Take());
152 while (const std::optional<std::string> message = reader_.Next()) {
153 if (!inbox_.Take(*message).ok()) {
154 connected_ = false;
155 return;
156 }
157 }
158 if (!reader_.status().ok() || !socket_->open()) {
159 connected_ = false;
160 }
161}
162
163void WebSocketLink::Send(const protocol::Input& input) {
164 if (connected_ && !socket_->Send(Frame(input)).ok()) {
165 connected_ = false;
166 }
167}
168
169} // namespace nanommo
void Append(std::string_view bytes)
Definition framing.cc:19
std::optional< std::string > Next()
Definition framing.cc:21
const absl::Status & status() const
Definition framing.h:32
WebSocket(const WebSocket &)=delete
std::string Take()
What's come since the last time.
absl::Status Send(std::string_view bytes)
void Wait(int milliseconds)
static absl::StatusOr< std::unique_ptr< WebSocket > > Open(const std::string &url)
Definition chat.cc:9
std::string Frame(const google::protobuf::MessageLite &message)
The size goes in front, as four bytes in network byte order.
Definition framing.cc:14
absl::StatusOr< protocol::LoginReply > AskOverWebSocket(const std::string &url, const protocol::LoginRequest &request)
The login server's answer to the request, through the gateway at url.