-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathServer.cpp
More file actions
288 lines (232 loc) · 8.19 KB
/
Server.cpp
File metadata and controls
288 lines (232 loc) · 8.19 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#include "Server.h"
#include <iostream>
#include <chrono>
#include <spdlog/spdlog.h>
namespace Walnut {
// Can only have one server instance per-process
static Server* s_Instance = nullptr;
Server::Server(int port)
: m_Port(port)
{
}
Server::~Server()
{
if (m_NetworkThread.joinable())
m_NetworkThread.join();
}
void Server::Start()
{
if (m_Running)
return;
m_NetworkThread = std::thread([this]() { NetworkThreadFunc(); });
}
void Server::Stop()
{
m_Running = false;
}
void Server::NetworkThreadFunc()
{
s_Instance = this;
m_Running = true;
SteamDatagramErrMsg errMsg;
if (!GameNetworkingSockets_Init(nullptr, errMsg))
{
OnFatalError(fmt::format("GameNetworkingSockets_Init failed: {}", errMsg));
return;
}
m_Interface = SteamNetworkingSockets();
// Start listening
SteamNetworkingIPAddr serverLocalAddress;
serverLocalAddress.Clear();
serverLocalAddress.m_port = m_Port;
SteamNetworkingConfigValue_t options;
options.SetPtr(k_ESteamNetworkingConfig_Callback_ConnectionStatusChanged, (void*)Server::ConnectionStatusChangedCallback);
// Try to start listen socket on port
m_ListenSocket = m_Interface->CreateListenSocketIP(serverLocalAddress, 1, &options);
if (m_ListenSocket == k_HSteamListenSocket_Invalid)
{
OnFatalError(fmt::format("Fatal error: Failed to listen on port {}", m_Port));
return;
}
// Try to create poll group
// TODO(Yan): should be optional, though good for groups which is probably the most common use case
m_PollGroup = m_Interface->CreatePollGroup();
if (m_PollGroup == k_HSteamNetPollGroup_Invalid)
{
OnFatalError(fmt::format("Fatal error: Failed to create poll group on port {}", m_Port));
return;
}
std::cout << "Server listening on port " << m_Port << std::endl;
while (m_Running)
{
PollIncomingMessages();
PollConnectionStateChanges();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
// Close all the connections
std::cout << "Closing connections..." << std::endl;
for (const auto& [clientID, clientInfo] : m_ConnectedClients)
{
m_Interface->CloseConnection(clientID, 0, "Server Shutdown", true);
}
m_ConnectedClients.clear();
m_Interface->CloseListenSocket(m_ListenSocket);
m_ListenSocket = k_HSteamListenSocket_Invalid;
m_Interface->DestroyPollGroup(m_PollGroup);
m_PollGroup = k_HSteamNetPollGroup_Invalid;
}
void Server::ConnectionStatusChangedCallback(SteamNetConnectionStatusChangedCallback_t* info) { s_Instance->OnConnectionStatusChanged(info); }
void Server::OnConnectionStatusChanged(SteamNetConnectionStatusChangedCallback_t* status)
{
// Handle connection state
switch (status->m_info.m_eState)
{
case k_ESteamNetworkingConnectionState_None:
// NOTE: We will get callbacks here when we destroy connections. You can ignore these.
break;
case k_ESteamNetworkingConnectionState_ClosedByPeer:
case k_ESteamNetworkingConnectionState_ProblemDetectedLocally:
{
// Ignore if they were not previously connected. (If they disconnected
// before we accepted the connection.)
if (status->m_eOldState == k_ESteamNetworkingConnectionState_Connected)
{
// Locate the client. Note that it should have been found, because this
// is the only codepath where we remove clients (except on shutdown),
// and connection change callbacks are dispatched in queue order.
auto itClient = m_ConnectedClients.find(status->m_hConn);
//assert(itClient != m_mapClients.end());
// Either ClosedByPeer or ProblemDetectedLocally - should be communicated to user callback
// User callback
m_ClientDisconnectedCallback(itClient->second);
m_ConnectedClients.erase(itClient);
}
else
{
//assert(info->m_eOldState == k_ESteamNetworkingConnectionState_Connecting);
}
// Clean up the connection. This is important!
// The connection is "closed" in the network sense, but
// it has not been destroyed. We must close it on our end, too
// to finish up. The reason information do not matter in this case,
// and we cannot linger because it's already closed on the other end,
// so we just pass 0s.
m_Interface->CloseConnection(status->m_hConn, 0, nullptr, false);
break;
}
case k_ESteamNetworkingConnectionState_Connecting:
{
// This must be a new connection
// assert(m_mapClients.find(info->m_hConn) == m_mapClients.end());
// Try to accept incoming connection
if (m_Interface->AcceptConnection(status->m_hConn) != k_EResultOK)
{
m_Interface->CloseConnection(status->m_hConn, 0, nullptr, false);
std::cout << "Couldn't accept connection (it was already closed?)" << std::endl;
break;
}
// Assign the poll group
if (!m_Interface->SetConnectionPollGroup(status->m_hConn, m_PollGroup))
{
m_Interface->CloseConnection(status->m_hConn, 0, nullptr, false);
std::cout << "Failed to set poll group" << std::endl;
break;
}
// Retrieve connection info
SteamNetConnectionInfo_t connectionInfo;
m_Interface->GetConnectionInfo(status->m_hConn, &connectionInfo);
// Register connected client
auto& client = m_ConnectedClients[status->m_hConn];
client.ID = (ClientID)status->m_hConn;
client.ConnectionDesc = connectionInfo.m_szConnectionDescription;
// User callback
m_ClientConnectedCallback(client);
break;
}
case k_ESteamNetworkingConnectionState_Connected:
// We will get a callback immediately after accepting the connection.
// Since we are the server, we can ignore this, it's not news to us.
break;
default:
break;
}
}
void Server::PollConnectionStateChanges()
{
m_Interface->RunCallbacks();
}
void Server::PollIncomingMessages()
{
// Process all messages
while (m_Running)
{
ISteamNetworkingMessage* incomingMessage = nullptr;
int messageCount = m_Interface->ReceiveMessagesOnPollGroup(m_PollGroup, &incomingMessage, 1);
if (messageCount == 0)
break;
if (messageCount < 0)
{
// messageCount < 0 means critical error?
m_Running = false;
return;
}
// assert(numMsgs == 1 && pIncomingMsg);
auto itClient = m_ConnectedClients.find(incomingMessage->m_conn);
if (itClient == m_ConnectedClients.end())
{
std::cout << "ERROR: Received data from unregistered client\n";
continue;
}
if (incomingMessage->m_cbSize)
m_DataReceivedCallback(itClient->second, Buffer(incomingMessage->m_pData, incomingMessage->m_cbSize));
// Release when done
incomingMessage->Release();
}
}
void Server::SetClientNick(HSteamNetConnection hConn, const char* nick)
{
// Set the connection name, too, which is useful for debugging
m_Interface->SetConnectionName(hConn, nick);
}
void Server::SetDataReceivedCallback(const DataReceivedCallback& function)
{
m_DataReceivedCallback = function;
}
void Server::SetClientConnectedCallback(const ClientConnectedCallback& function)
{
m_ClientConnectedCallback = function;
}
void Server::SetClientDisconnectedCallback(const ClientDisconnectedCallback& function)
{
m_ClientDisconnectedCallback = function;
}
void Server::SendBufferToClient(ClientID clientID, Buffer buffer, bool reliable)
{
m_Interface->SendMessageToConnection((HSteamNetConnection)clientID, buffer.Data, (ClientID)buffer.Size, reliable ? k_nSteamNetworkingSend_Reliable : k_nSteamNetworkingSend_Unreliable, nullptr);
}
void Server::SendBufferToAllClients(Buffer buffer, ClientID excludeClientID, bool reliable)
{
for (const auto& [clientID, clientInfo] : m_ConnectedClients)
{
if (clientID != excludeClientID)
SendBufferToClient(clientID, buffer, reliable);
}
}
void Server::SendStringToClient(ClientID clientID, const std::string& string, bool reliable)
{
SendBufferToClient(clientID, Buffer(string.data(), string.size()), reliable);
}
void Server::SendStringToAllClients(const std::string& string, ClientID excludeClientID, bool reliable)
{
SendBufferToAllClients(Buffer(string.data(), string.size()), excludeClientID, reliable);
}
void Server::KickClient(ClientID clientID)
{
m_Interface->CloseConnection(clientID, 0, "Kicked by host", false);
}
void Server::OnFatalError(const std::string& message)
{
std::cout << message << std::endl;
m_Running = false;
}
}