KcpServer.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. // kcp server logic abstracted into a class.
  2. // for use in Mirror, DOTSNET, testing, etc.
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. namespace kcp2k
  8. {
  9. public class KcpServer
  10. {
  11. // events
  12. public Action<int> OnConnected;
  13. public Action<int, ArraySegment<byte>, KcpChannel> OnData;
  14. public Action<int> OnDisconnected;
  15. // socket configuration
  16. // DualMode uses both IPv6 and IPv4. not all platforms support it.
  17. // (Nintendo Switch, etc.)
  18. public bool DualMode;
  19. // too small send/receive buffers might cause connection drops under
  20. // heavy load. using the OS max size can make a difference already.
  21. public bool MaximizeSendReceiveBuffersToOSLimit;
  22. // kcp configuration
  23. // NoDelay is recommended to reduce latency. This also scales better
  24. // without buffers getting full.
  25. public bool NoDelay;
  26. // KCP internal update interval. 100ms is KCP default, but a lower
  27. // interval is recommended to minimize latency and to scale to more
  28. // networked entities.
  29. public uint Interval;
  30. // KCP fastresend parameter. Faster resend for the cost of higher
  31. // bandwidth.
  32. public int FastResend;
  33. // KCP 'NoCongestionWindow' is false by default. here we negate it for
  34. // ease of use. This can be disabled for high scale games if connections
  35. // choke regularly.
  36. public bool CongestionWindow;
  37. // KCP window size can be modified to support higher loads.
  38. // for example, Mirror Benchmark requires:
  39. // 128, 128 for 4k monsters
  40. // 512, 512 for 10k monsters
  41. // 8192, 8192 for 20k monsters
  42. public uint SendWindowSize;
  43. public uint ReceiveWindowSize;
  44. // timeout in milliseconds
  45. public int Timeout;
  46. // maximum retransmission attempts until dead_link
  47. public uint MaxRetransmits;
  48. // state
  49. protected Socket socket;
  50. EndPoint newClientEP;
  51. // IMPORTANT: raw receive buffer always needs to be of 'MTU' size, even
  52. // if MaxMessageSize is larger. kcp always sends in MTU
  53. // segments and having a buffer smaller than MTU would
  54. // silently drop excess data.
  55. // => we need the mtu to fit channel + message!
  56. readonly byte[] rawReceiveBuffer = new byte[Kcp.MTU_DEF];
  57. // connections <connectionId, connection> where connectionId is EndPoint.GetHashCode
  58. public Dictionary<int, KcpServerConnection> connections = new Dictionary<int, KcpServerConnection>();
  59. public KcpServer(Action<int> OnConnected,
  60. Action<int, ArraySegment<byte>, KcpChannel> OnData,
  61. Action<int> OnDisconnected,
  62. bool DualMode,
  63. bool NoDelay,
  64. uint Interval,
  65. int FastResend = 0,
  66. bool CongestionWindow = true,
  67. uint SendWindowSize = Kcp.WND_SND,
  68. uint ReceiveWindowSize = Kcp.WND_RCV,
  69. int Timeout = KcpConnection.DEFAULT_TIMEOUT,
  70. uint MaxRetransmits = Kcp.DEADLINK,
  71. bool MaximizeSendReceiveBuffersToOSLimit = false)
  72. {
  73. this.OnConnected = OnConnected;
  74. this.OnData = OnData;
  75. this.OnDisconnected = OnDisconnected;
  76. this.DualMode = DualMode;
  77. this.NoDelay = NoDelay;
  78. this.Interval = Interval;
  79. this.FastResend = FastResend;
  80. this.CongestionWindow = CongestionWindow;
  81. this.SendWindowSize = SendWindowSize;
  82. this.ReceiveWindowSize = ReceiveWindowSize;
  83. this.Timeout = Timeout;
  84. this.MaxRetransmits = MaxRetransmits;
  85. this.MaximizeSendReceiveBuffersToOSLimit = MaximizeSendReceiveBuffersToOSLimit;
  86. // create newClientEP either IPv4 or IPv6
  87. newClientEP = DualMode
  88. ? new IPEndPoint(IPAddress.IPv6Any, 0)
  89. : new IPEndPoint(IPAddress.Any, 0);
  90. }
  91. public bool IsActive() => socket != null;
  92. // if connections drop under heavy load, increase to OS limit.
  93. // if still not enough, increase the OS limit.
  94. void ConfigureSocketBufferSizes()
  95. {
  96. if (MaximizeSendReceiveBuffersToOSLimit)
  97. {
  98. // log initial size for comparison.
  99. // remember initial size for log comparison
  100. int initialReceive = socket.ReceiveBufferSize;
  101. int initialSend = socket.SendBufferSize;
  102. socket.SetReceiveBufferToOSLimit();
  103. socket.SetSendBufferToOSLimit();
  104. Log.Info($"KcpServer: RecvBuf = {initialReceive}=>{socket.ReceiveBufferSize} ({socket.ReceiveBufferSize/initialReceive}x) SendBuf = {initialSend}=>{socket.SendBufferSize} ({socket.SendBufferSize/initialSend}x) increased to OS limits!");
  105. }
  106. // otherwise still log the defaults for info.
  107. else Log.Info($"KcpServer: RecvBuf = {socket.ReceiveBufferSize} SendBuf = {socket.SendBufferSize}. If connections drop under heavy load, enable {nameof(MaximizeSendReceiveBuffersToOSLimit)} to increase it to OS limit. If they still drop, increase the OS limit.");
  108. }
  109. public void Start(ushort port)
  110. {
  111. // only start once
  112. if (socket != null)
  113. {
  114. Log.Warning("KCP: server already started!");
  115. }
  116. // listen
  117. if (DualMode)
  118. {
  119. // IPv6 socket with DualMode
  120. socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
  121. socket.DualMode = true;
  122. socket.Bind(new IPEndPoint(IPAddress.IPv6Any, port));
  123. }
  124. else
  125. {
  126. // IPv4 socket
  127. socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  128. socket.Bind(new IPEndPoint(IPAddress.Any, port));
  129. }
  130. // configure socket buffer size.
  131. ConfigureSocketBufferSizes();
  132. }
  133. public void Send(int connectionId, ArraySegment<byte> segment, KcpChannel channel)
  134. {
  135. if (connections.TryGetValue(connectionId, out KcpServerConnection connection))
  136. {
  137. connection.SendData(segment, channel);
  138. }
  139. }
  140. public void Disconnect(int connectionId)
  141. {
  142. if (connections.TryGetValue(connectionId, out KcpServerConnection connection))
  143. {
  144. connection.Disconnect();
  145. }
  146. }
  147. public string GetClientAddress(int connectionId)
  148. {
  149. if (connections.TryGetValue(connectionId, out KcpServerConnection connection))
  150. {
  151. return (connection.GetRemoteEndPoint() as IPEndPoint).Address.ToString();
  152. }
  153. return "";
  154. }
  155. // EndPoint & Receive functions can be overwritten for where-allocation:
  156. // https://github.com/vis2k/where-allocation
  157. protected virtual int ReceiveFrom(byte[] buffer, out int connectionHash)
  158. {
  159. // NOTE: ReceiveFrom allocates.
  160. // we pass our IPEndPoint to ReceiveFrom.
  161. // receive from calls newClientEP.Create(socketAddr).
  162. // IPEndPoint.Create always returns a new IPEndPoint.
  163. // https://github.com/mono/mono/blob/f74eed4b09790a0929889ad7fc2cf96c9b6e3757/mcs/class/System/System.Net.Sockets/Socket.cs#L1761
  164. int read = socket.ReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref newClientEP);
  165. // calculate connectionHash from endpoint
  166. // NOTE: IPEndPoint.GetHashCode() allocates.
  167. // it calls m_Address.GetHashCode().
  168. // m_Address is an IPAddress.
  169. // GetHashCode() allocates for IPv6:
  170. // https://github.com/mono/mono/blob/bdd772531d379b4e78593587d15113c37edd4a64/mcs/class/referencesource/System/net/System/Net/IPAddress.cs#L699
  171. //
  172. // => using only newClientEP.Port wouldn't work, because
  173. // different connections can have the same port.
  174. connectionHash = newClientEP.GetHashCode();
  175. return read;
  176. }
  177. protected virtual KcpServerConnection CreateConnection() =>
  178. new KcpServerConnection(socket, newClientEP, NoDelay, Interval, FastResend, CongestionWindow, SendWindowSize, ReceiveWindowSize, Timeout, MaxRetransmits);
  179. // process incoming messages. should be called before updating the world.
  180. HashSet<int> connectionsToRemove = new HashSet<int>();
  181. public void TickIncoming()
  182. {
  183. while (socket != null && socket.Poll(0, SelectMode.SelectRead))
  184. {
  185. try
  186. {
  187. // receive
  188. int msgLength = ReceiveFrom(rawReceiveBuffer, out int connectionId);
  189. //Log.Info($"KCP: server raw recv {msgLength} bytes = {BitConverter.ToString(buffer, 0, msgLength)}");
  190. // IMPORTANT: detect if buffer was too small for the received
  191. // msgLength. otherwise the excess data would be
  192. // silently lost.
  193. // (see ReceiveFrom documentation)
  194. if (msgLength <= rawReceiveBuffer.Length)
  195. {
  196. // is this a new connection?
  197. if (!connections.TryGetValue(connectionId, out KcpServerConnection connection))
  198. {
  199. // create a new KcpConnection based on last received
  200. // EndPoint. can be overwritten for where-allocation.
  201. connection = CreateConnection();
  202. // DO NOT add to connections yet. only if the first message
  203. // is actually the kcp handshake. otherwise it's either:
  204. // * random data from the internet
  205. // * or from a client connection that we just disconnected
  206. // but that hasn't realized it yet, still sending data
  207. // from last session that we should absolutely ignore.
  208. //
  209. //
  210. // TODO this allocates a new KcpConnection for each new
  211. // internet connection. not ideal, but C# UDP Receive
  212. // already allocated anyway.
  213. //
  214. // expecting a MAGIC byte[] would work, but sending the raw
  215. // UDP message without kcp's reliability will have low
  216. // probability of being received.
  217. //
  218. // for now, this is fine.
  219. // setup authenticated event that also adds to connections
  220. connection.OnAuthenticated = () =>
  221. {
  222. // only send handshake to client AFTER we received his
  223. // handshake in OnAuthenticated.
  224. // we don't want to reply to random internet messages
  225. // with handshakes each time.
  226. connection.SendHandshake();
  227. // add to connections dict after being authenticated.
  228. connections.Add(connectionId, connection);
  229. Log.Info($"KCP: server added connection({connectionId})");
  230. // setup Data + Disconnected events only AFTER the
  231. // handshake. we don't want to fire OnServerDisconnected
  232. // every time we receive invalid random data from the
  233. // internet.
  234. // setup data event
  235. connection.OnData = (message, channel) =>
  236. {
  237. // call mirror event
  238. //Log.Info($"KCP: OnServerDataReceived({connectionId}, {BitConverter.ToString(message.Array, message.Offset, message.Count)})");
  239. OnData.Invoke(connectionId, message, channel);
  240. };
  241. // setup disconnected event
  242. connection.OnDisconnected = () =>
  243. {
  244. // flag for removal
  245. // (can't remove directly because connection is updated
  246. // and event is called while iterating all connections)
  247. connectionsToRemove.Add(connectionId);
  248. // call mirror event
  249. Log.Info($"KCP: OnServerDisconnected({connectionId})");
  250. OnDisconnected.Invoke(connectionId);
  251. };
  252. // finally, call mirror OnConnected event
  253. Log.Info($"KCP: OnServerConnected({connectionId})");
  254. OnConnected.Invoke(connectionId);
  255. };
  256. // now input the message & process received ones
  257. // connected event was set up.
  258. // tick will process the first message and adds the
  259. // connection if it was the handshake.
  260. connection.RawInput(rawReceiveBuffer, msgLength);
  261. connection.TickIncoming();
  262. // again, do not add to connections.
  263. // if the first message wasn't the kcp handshake then
  264. // connection will simply be garbage collected.
  265. }
  266. // existing connection: simply input the message into kcp
  267. else
  268. {
  269. connection.RawInput(rawReceiveBuffer, msgLength);
  270. }
  271. }
  272. else
  273. {
  274. Log.Error($"KCP Server: message of size {msgLength} does not fit into buffer of size {rawReceiveBuffer.Length}. The excess was silently dropped. Disconnecting connectionId={connectionId}.");
  275. Disconnect(connectionId);
  276. }
  277. }
  278. // this is fine, the socket might have been closed in the other end
  279. catch (SocketException) {}
  280. }
  281. // process inputs for all server connections
  282. // (even if we didn't receive anything. need to tick ping etc.)
  283. foreach (KcpServerConnection connection in connections.Values)
  284. {
  285. connection.TickIncoming();
  286. }
  287. // remove disconnected connections
  288. // (can't do it in connection.OnDisconnected because Tick is called
  289. // while iterating connections)
  290. foreach (int connectionId in connectionsToRemove)
  291. {
  292. connections.Remove(connectionId);
  293. }
  294. connectionsToRemove.Clear();
  295. }
  296. // process outgoing messages. should be called after updating the world.
  297. public void TickOutgoing()
  298. {
  299. // flush all server connections
  300. foreach (KcpServerConnection connection in connections.Values)
  301. {
  302. connection.TickOutgoing();
  303. }
  304. }
  305. // process incoming and outgoing for convenience.
  306. // => ideally call ProcessIncoming() before updating the world and
  307. // ProcessOutgoing() after updating the world for minimum latency
  308. public void Tick()
  309. {
  310. TickIncoming();
  311. TickOutgoing();
  312. }
  313. public void Stop()
  314. {
  315. socket?.Close();
  316. socket = null;
  317. }
  318. }
  319. }