-
Notifications
You must be signed in to change notification settings - Fork 21
/
NextServer.cs
190 lines (168 loc) · 5.8 KB
/
NextServer.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
using Steamworks;
using Steamworks.Data;
using System;
using UnityEngine;
namespace Mirror.FizzySteam
{
public class NextServer : NextCommon, IServer
{
private event Action<int> OnConnected;
private event Action<int, byte[], int> OnReceivedData;
private event Action<int> OnDisconnected;
private event Action<int, Exception> OnReceivedError;
private BidirectionalDictionary<Connection, int> connToMirrorID;
private BidirectionalDictionary<SteamId, int> steamIDToMirrorID;
private int maxConnections;
private int nextConnectionID;
private FizzySocketManager listenSocket;
private NextServer(int maxConnections)
{
this.maxConnections = maxConnections;
connToMirrorID = new BidirectionalDictionary<Connection, int>();
steamIDToMirrorID = new BidirectionalDictionary<SteamId, int>();
nextConnectionID = 1;
SteamNetworkingSockets.OnConnectionStatusChanged += OnConnectionStatusChanged;
}
public static NextServer CreateServer(FizzyFacepunch transport, int maxConnections)
{
NextServer s = new NextServer(maxConnections);
s.OnConnected += (id) => transport.OnServerConnected.Invoke(id);
s.OnDisconnected += (id) => transport.OnServerDisconnected.Invoke(id);
s.OnReceivedData += (id, data, ch) => transport.OnServerDataReceived.Invoke(id, new ArraySegment<byte>(data), ch);
s.OnReceivedError += (id, exception) => transport.OnServerError.Invoke(id, TransportError.Unexpected, exception.ToString());
if (!SteamClient.IsValid)
{
Debug.LogError("SteamWorks not initialized.");
}
s.Host();
return s;
}
private void Host()
{
listenSocket = SteamNetworkingSockets.CreateRelaySocket<FizzySocketManager>();
listenSocket.ForwardMessage = OnMessageReceived;
}
private void OnConnectionStatusChanged(Connection conn, ConnectionInfo info)
{
ulong clientSteamID = info.Identity.SteamId;
if (info.State == ConnectionState.Connecting)
{
if (connToMirrorID.Count >= maxConnections)
{
Debug.Log($"Incoming connection {clientSteamID} would exceed max connection count. Rejecting.");
conn.Close(false, 0, "Max Connection Count");
return;
}
Result res;
if((res = conn.Accept()) == Result.OK)
{
Debug.Log($"Accepting connection {clientSteamID}");
}
else
{
Debug.Log($"Connection {clientSteamID} could not be accepted: {res.ToString()}");
}
}
else if (info.State == ConnectionState.Connected)
{
int connectionId = nextConnectionID++;
connToMirrorID.Add(conn, connectionId);
steamIDToMirrorID.Add(clientSteamID, connectionId);
OnConnected.Invoke(connectionId);
Debug.Log($"Client with SteamID {clientSteamID} connected. Assigning connection id {connectionId}");
}
else if(info.State == ConnectionState.ClosedByPeer)
{
if (connToMirrorID.TryGetValue(conn, out int connId))
{
InternalDisconnect(connId, conn);
}
}
else
{
Debug.Log($"Connection {clientSteamID} state changed: {info.State.ToString()}");
}
}
private void InternalDisconnect(int connId, Connection socket)
{
OnDisconnected.Invoke(connId);
socket.Close(false, 0, "Graceful disconnect");
connToMirrorID.Remove(connId);
steamIDToMirrorID.Remove(connId);
Debug.Log($"Client with SteamID {connId} disconnected.");
}
public void Disconnect(int connectionId)
{
if (connToMirrorID.TryGetValue(connectionId, out Connection conn))
{
Debug.Log($"Connection id {connectionId} disconnected.");
conn.Close(false, 0, "Disconnected by server");
steamIDToMirrorID.Remove(connectionId);
connToMirrorID.Remove(connectionId);
OnDisconnected(connectionId);
}
else
{
Debug.LogWarning("Trying to disconnect unknown connection id: " + connectionId);
}
}
public void FlushData()
{
foreach (Connection conn in connToMirrorID.FirstTypes)
{
conn.Flush();
}
}
public void ReceiveData()
{
listenSocket.Receive(MAX_MESSAGES);
}
private void OnMessageReceived(Connection conn, IntPtr dataPtr, int size)
{
(byte[] data, int ch) = ProcessMessage(dataPtr, size);
OnReceivedData(connToMirrorID[conn], data, ch);
}
public void Send(int connectionId, byte[] data, int channelId)
{
if (connToMirrorID.TryGetValue(connectionId, out Connection conn))
{
Result res = SendSocket(conn, data, channelId);
if (res == Result.NoConnection || res == Result.InvalidParam)
{
Debug.Log($"Connection to {connectionId} was lost.");
InternalDisconnect(connectionId, conn);
}
else if (res != Result.OK)
{
Debug.LogError($"Could not send: {res.ToString()}");
}
}
else
{
Debug.LogError("Trying to send on unknown connection: " + connectionId);
OnReceivedError.Invoke(connectionId, new Exception("ERROR Unknown Connection"));
}
}
public string ServerGetClientAddress(int connectionId)
{
if (steamIDToMirrorID.TryGetValue(connectionId, out SteamId steamId))
{
return steamId.ToString();
}
else
{
Debug.LogError("Trying to get info on unknown connection: " + connectionId);
OnReceivedError.Invoke(connectionId, new Exception("ERROR Unknown Connection"));
return string.Empty;
}
}
public void Shutdown()
{
if(listenSocket != null)
{
SteamNetworkingSockets.OnConnectionStatusChanged -= OnConnectionStatusChanged;
listenSocket.Close();
}
}
}
}