forked from sagering/UnityNetcodeSteamP2PRelayTransport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSteamP2PRelayTransport.cs
334 lines (288 loc) · 10.9 KB
/
SteamP2PRelayTransport.cs
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using Unity.Netcode;
using UnityEngine;
using Steamworks;
using Steamworks.Data;
public class SteamP2PRelayTransport : NetworkTransport
{
/// <summary>
/// For clients, this is the steam id we want to connect to.
/// </summary>
public ulong serverId = 0;
/// <summary>
/// Enables additional debug logs.
/// </summary>
public bool debug = false;
class ClientCallbacks : IConnectionManager
{
SteamP2PRelayTransport transport;
// TODO: Increase buffer size.
byte[] buffer = new byte[1024];
ArraySegment<byte> emptyPayload = new ArraySegment<byte>();
public ClientCallbacks(SteamP2PRelayTransport transport)
{
this.transport = transport;
}
/// <summary>
/// We started connecting to this guy
/// </summary>
public void OnConnecting(ConnectionInfo info)
{
Debug.Log("ClientCallbacks: OnConnecting");
}
/// <summary>
/// Called when the connection is fully connected and can start being communicated with
/// </summary>
public void OnConnected(ConnectionInfo info)
{
Debug.Log("ClientCallbacks: OnConnected");
transport.InvokeOnTransportEvent(NetworkEvent.Connect, transport.ServerClientId, emptyPayload, Time.realtimeSinceStartup);
}
/// <summary>
/// We got disconnected
/// </summary>
public void OnDisconnected(ConnectionInfo info)
{
Debug.Log("ClientCallbacks: OnDisconnected");
transport.InvokeOnTransportEvent(NetworkEvent.Disconnect, transport.ServerClientId, emptyPayload, Time.realtimeSinceStartup);
}
/// <summary>
/// Received a message
/// </summary>
public unsafe void OnMessage(IntPtr data, int size, long messageNum, long recvTime, int channel)
{
Debug.Log("ClientCallbacks: OnMessage");
// TODO: Assert that size <= buffer size
Marshal.Copy(data, buffer, 0, size);
transport.InvokeOnTransportEvent(NetworkEvent.Data, transport.ServerClientId, new ArraySegment<byte>(buffer, 0, size), Time.realtimeSinceStartup);
}
}
class ServerCallbacks : ISocketManager
{
SteamP2PRelayTransport transport;
// TODO: Increase buffer size.
byte[] buffer = new byte[1024];
ArraySegment<byte> emptyPayload = new ArraySegment<byte>();
public ServerCallbacks(SteamP2PRelayTransport transport)
{
Debug.Log("Instantiating ServerCallbacks");
this.transport = transport;
}
/// <summary>
/// Must call Accept or Close on the connection within a second or so
/// </summary>
public void OnConnecting(Connection connection, ConnectionInfo info)
{
Debug.Log("ServerCallbacks: OnConnecting");
connection.Accept();
}
/// <summary>
/// Called when the connection is fully connected and can start being communicated with
/// </summary>
public void OnConnected(Connection connection, ConnectionInfo info)
{
Debug.Log("ServerCallbacks: OnConnected");
transport.InvokeOnTransportEvent(NetworkEvent.Connect, connection.Id, emptyPayload, Time.realtimeSinceStartup);
}
/// <summary>
/// Called when the connection leaves. Must call Close on the connection
/// </summary>
public void OnDisconnected(Connection connection, ConnectionInfo info)
{
Debug.Log("ServerCallbacks: OnDisconnected");
connection.Close();
transport.InvokeOnTransportEvent(NetworkEvent.Connect, connection.Id, emptyPayload, Time.realtimeSinceStartup);
}
/// <summary>
/// Received a message from a connection
/// </summary>
public void OnMessage(Connection connection, NetIdentity identity, IntPtr data, int size, long messageNum, long recvTime, int channel)
{
Debug.Log("ServerCallbacks: OnMessage");
// TODO: Assert that size <= buffer size
Marshal.Copy(data, buffer, 0, size);
transport.InvokeOnTransportEvent(NetworkEvent.Data, connection.Id, new ArraySegment<byte>(buffer, 0, size), Time.realtimeSinceStartup);
}
}
private bool isClient = false;
private SocketManager socketManager = null;
private ConnectionManager clientConnection = null;
/// <summary>
/// A constant `clientId` that represents the server
/// When this value is found in methods such as `Send`, it should be treated as a placeholder that means "the server"
/// </summary>
override public ulong ServerClientId { get => 0; }
/// <summary>
/// Send a payload to the specified clientId, data and channelName.
/// </summary>
/// <param name="clientId">The clientId to send to</param>
/// <param name="payload">The data to send</param>
/// <param name="networkDelivery">The delivery type (QoS) to send data with</param>
public override void Send(ulong clientId, ArraySegment<byte> payload, NetworkDelivery networkDelivery)
{
SendType sendType = CastToSendType(networkDelivery);
if (isClient)
{
clientConnection?.Connection.SendMessage(payload.Array, payload.Offset, payload.Count, sendType);
}
else
{
if (socketManager == null) return;
foreach (var connection in socketManager.Connected)
{
if (connection.Id != clientId) continue;
connection.SendMessage(payload.Array, payload.Offset, payload.Count, sendType);
}
}
}
/// <summary>
/// Polls for incoming events, with an extra output parameter to report the precise time the event was received.
/// </summary>
/// <param name="clientId">The clientId this event is for</param>
/// <param name="payload">The incoming data payload</param>
/// <param name="receiveTime">The time the event was received, as reported by Time.realtimeSinceStartup.</param>
/// <returns>Returns the event type</returns>
override public NetworkEvent PollEvent(out ulong clientId, out ArraySegment<byte> payload, out float receiveTime)
{
clientId = 0;
receiveTime = Time.realtimeSinceStartup;
return NetworkEvent.Nothing;
}
/// <summary>
/// Connects client to the server
/// </summary>
override public bool StartClient()
{
try
{
clientConnection =
Steamworks.SteamNetworkingSockets.ConnectRelay<ConnectionManager>(serverId, 0);
clientConnection.Interface = new ClientCallbacks(this);
isClient = true;
return true;
}
catch (Exception e)
{
Debug.LogError("StartClient failed with exception " + e);
return false;
}
}
/// <summary>
/// Starts to listening for incoming clients
/// </summary>
override public bool StartServer()
{
try
{
socketManager = Steamworks.SteamNetworkingSockets.CreateRelaySocket<SocketManager>(0);
socketManager.Interface = new ServerCallbacks(this);
return true;
}
catch (Exception e)
{
Debug.LogError("StartServer failed with exception " + e);
return false;
}
}
/// <summary>
/// Disconnects a client from the server
/// </summary>
/// <param name="clientId">The clientId to disconnect</param>
override public void DisconnectRemoteClient(ulong clientId)
{
Debug.Log("DisconnectRemoteClient.");
if (socketManager == null) return;
foreach (var connection in socketManager.Connected)
{
if (connection.Id != clientId) continue;
connection.Close();
}
}
/// <summary>
/// Disconnects the local client from the server
/// </summary>
override public void DisconnectLocalClient()
{
Debug.Log("DisconnectLocalClient.");
clientConnection?.Close();
}
/// <summary>
/// Gets the round trip time for a specific client. This method is optional
/// </summary>
/// <param name="clientId">The clientId to get the RTT from</param>
/// <returns>Returns the round trip time in milliseconds </returns>
override public ulong GetCurrentRtt(ulong clientId) { return 0; }
/// <summary>
/// Shuts down the transport
/// </summary>
override public void Shutdown()
{
Debug.Log("Shutdown.");
Steamworks.SteamClient.Shutdown();
}
/// <summary>
/// Initializes the transport
/// </summary>
override public void Initialize()
{
Debug.Log("Initialize.");
Steamworks.SteamNetworkingUtils.InitRelayNetworkAccess();
if (debug)
{
SteamNetworkingUtils.DebugLevel = NetDebugOutput.Debug;
SteamNetworkingUtils.OnDebugOutput += DebugOutput;
}
}
void LateUpdate()
{
socketManager?.Receive();
clientConnection?.Receive();
}
static SendType CastToSendType(NetworkDelivery networkDelivery)
{
// TODO: This mapping might need to be revised.
SendType sendType = SendType.Unreliable;
switch (networkDelivery)
{
/// <summary>
/// Unreliable message
/// </summary>
case NetworkDelivery.Unreliable:
break;
/// <summary>
/// Unreliable with sequencing
/// </summary>
case NetworkDelivery.UnreliableSequenced:
break;
/// <summary>
/// Reliable message
/// </summary>
case NetworkDelivery.Reliable:
sendType |= SendType.Reliable;
break;
/// <summary>
/// Reliable message where messages are guaranteed to be in the right order
/// </summary>
case NetworkDelivery.ReliableSequenced:
sendType |= SendType.Reliable;
break;
/// <summary>
/// A reliable message with guaranteed order with fragmentation support
/// </summary>
case NetworkDelivery.ReliableFragmentedSequenced:
sendType |= SendType.Reliable;
break;
default:
break;
}
return sendType;
}
void DebugOutput(NetDebugOutput type, string text)
{
Debug.Log(text);
}
}