NetworkConnection.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace Mirror
  5. {
  6. /// <summary>Base NetworkConnection class for server-to-client and client-to-server connection.</summary>
  7. public abstract class NetworkConnection
  8. {
  9. public const int LocalConnectionId = 0;
  10. // NetworkIdentities that this connection can see
  11. // TODO move to server's NetworkConnectionToClient?
  12. internal readonly HashSet<NetworkIdentity> observing = new HashSet<NetworkIdentity>();
  13. /// <summary>Unique identifier for this connection that is assigned by the transport layer.</summary>
  14. // assigned by transport, this id is unique for every connection on server.
  15. // clients don't know their own id and they don't know other client's ids.
  16. public readonly int connectionId;
  17. /// <summary>Flag that indicates the client has been authenticated.</summary>
  18. public bool isAuthenticated;
  19. /// <summary>General purpose object to hold authentication data, character selection, tokens, etc.</summary>
  20. public object authenticationData;
  21. /// <summary>A server connection is ready after joining the game world.</summary>
  22. // TODO move this to ConnectionToClient so the flag only lives on server
  23. // connections? clients could use NetworkClient.ready to avoid redundant
  24. // state.
  25. public bool isReady;
  26. /// <summary>IP address of the connection. Can be useful for game master IP bans etc.</summary>
  27. public abstract string address { get; }
  28. /// <summary>Last time a message was received for this connection. Includes system and user messages.</summary>
  29. public float lastMessageTime;
  30. /// <summary>This connection's main object (usually the player object).</summary>
  31. public NetworkIdentity identity { get; internal set; }
  32. /// <summary>All NetworkIdentities owned by this connection. Can be main player, pets, etc.</summary>
  33. // IMPORTANT: this needs to be <NetworkIdentity>, not <uint netId>.
  34. // fixes a bug where DestroyOwnedObjects wouldn't find the
  35. // netId anymore: https://github.com/vis2k/Mirror/issues/1380
  36. // Works fine with NetworkIdentity pointers though.
  37. public readonly HashSet<NetworkIdentity> clientOwnedObjects = new HashSet<NetworkIdentity>();
  38. // batching from server to client & client to server.
  39. // fewer transport calls give us significantly better performance/scale.
  40. //
  41. // for a 64KB max message transport and 64 bytes/message on average, we
  42. // reduce transport calls by a factor of 1000.
  43. //
  44. // depending on the transport, this can give 10x performance.
  45. //
  46. // Dictionary<channelId, batch> because we have multiple channels.
  47. protected Dictionary<int, Batcher> batches = new Dictionary<int, Batcher>();
  48. /// <summary>last batch's remote timestamp. not interpolated. useful for NetworkTransform etc.</summary>
  49. // for any given NetworkMessage/Rpc/Cmd/OnSerialize, this was the time
  50. // on the REMOTE END when it was sent.
  51. //
  52. // NOTE: this is NOT in NetworkTime, it needs to be per-connection
  53. // because the server receives different batch timestamps from
  54. // different connections.
  55. public double remoteTimeStamp { get; internal set; }
  56. internal NetworkConnection()
  57. {
  58. // set lastTime to current time when creating connection to make
  59. // sure it isn't instantly kicked for inactivity
  60. lastMessageTime = Time.time;
  61. }
  62. internal NetworkConnection(int networkConnectionId) : this()
  63. {
  64. connectionId = networkConnectionId;
  65. // TODO why isn't lastMessageTime set in here like in the other ctor?
  66. }
  67. // TODO if we only have Reliable/Unreliable, then we could initialize
  68. // two batches and avoid this code
  69. protected Batcher GetBatchForChannelId(int channelId)
  70. {
  71. // get existing or create new writer for the channelId
  72. Batcher batch;
  73. if (!batches.TryGetValue(channelId, out batch))
  74. {
  75. // get max batch size for this channel
  76. int threshold = Transport.activeTransport.GetBatchThreshold(channelId);
  77. // create batcher
  78. batch = new Batcher(threshold);
  79. batches[channelId] = batch;
  80. }
  81. return batch;
  82. }
  83. // validate packet size before sending. show errors if too big/small.
  84. // => it's best to check this here, we can't assume that all transports
  85. // would check max size and show errors internally. best to do it
  86. // in one place in Mirror.
  87. // => it's important to log errors, so the user knows what went wrong.
  88. protected static bool ValidatePacketSize(ArraySegment<byte> segment, int channelId)
  89. {
  90. int max = Transport.activeTransport.GetMaxPacketSize(channelId);
  91. if (segment.Count > max)
  92. {
  93. Debug.LogError($"NetworkConnection.ValidatePacketSize: cannot send packet larger than {max} bytes, was {segment.Count} bytes");
  94. return false;
  95. }
  96. if (segment.Count == 0)
  97. {
  98. // zero length packets getting into the packet queues are bad.
  99. Debug.LogError("NetworkConnection.ValidatePacketSize: cannot send zero bytes");
  100. return false;
  101. }
  102. // good size
  103. return true;
  104. }
  105. // Send stage one: NetworkMessage<T>
  106. /// <summary>Send a NetworkMessage to this connection over the given channel.</summary>
  107. public void Send<T>(T message, int channelId = Channels.Reliable)
  108. where T : struct, NetworkMessage
  109. {
  110. using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter())
  111. {
  112. // pack message and send allocation free
  113. MessagePacking.Pack(message, writer);
  114. NetworkDiagnostics.OnSend(message, channelId, writer.Position, 1);
  115. Send(writer.ToArraySegment(), channelId);
  116. }
  117. }
  118. // Send stage two: serialized NetworkMessage as ArraySegment<byte>
  119. // internal because no one except Mirror should send bytes directly to
  120. // the client. they would be detected as a message. send messages instead.
  121. internal virtual void Send(ArraySegment<byte> segment, int channelId = Channels.Reliable)
  122. {
  123. //Debug.Log("ConnectionSend " + this + " bytes:" + BitConverter.ToString(segment.Array, segment.Offset, segment.Count));
  124. // add to batch no matter what.
  125. // batching will try to fit as many as possible into MTU.
  126. // but we still allow > MTU, e.g. kcp max packet size 144kb.
  127. // those are simply sent as single batches.
  128. //
  129. // IMPORTANT: do NOT send > batch sized messages directly:
  130. // - data race: large messages would be sent directly. small
  131. // messages would be sent in the batch at the end of frame
  132. // - timestamps: if batching assumes a timestamp, then large
  133. // messages need that too.
  134. //
  135. // NOTE: we ALWAYS batch. it's not optional, because the
  136. // receiver needs timestamps for NT etc.
  137. //
  138. // NOTE: we do NOT ValidatePacketSize here yet. the final packet
  139. // will be the full batch, including timestamp.
  140. GetBatchForChannelId(channelId).AddMessage(segment);
  141. }
  142. // Send stage three: hand off to transport
  143. protected abstract void SendToTransport(ArraySegment<byte> segment, int channelId = Channels.Reliable);
  144. // flush batched messages at the end of every Update.
  145. internal virtual void Update()
  146. {
  147. // go through batches for all channels
  148. foreach (KeyValuePair<int, Batcher> kvp in batches)
  149. {
  150. // make and send as many batches as necessary from the stored
  151. // messages.
  152. Batcher batcher = kvp.Value;
  153. using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter())
  154. {
  155. // make a batch with our local time (double precision)
  156. while (batcher.MakeNextBatch(writer, NetworkTime.localTime))
  157. {
  158. // validate packet before handing the batch to the
  159. // transport. this guarantees that we always stay
  160. // within transport's max message size limit.
  161. // => just in case transport forgets to check it
  162. // => just in case mirror miscalulated it etc.
  163. ArraySegment<byte> segment = writer.ToArraySegment();
  164. if (ValidatePacketSize(segment, kvp.Key))
  165. {
  166. // send to transport
  167. SendToTransport(segment, kvp.Key);
  168. //UnityEngine.Debug.Log($"sending batch of {writer.Position} bytes for channel={kvp.Key} connId={connectionId}");
  169. // reset writer for each new batch
  170. writer.Position = 0;
  171. }
  172. }
  173. }
  174. }
  175. }
  176. /// <summary>Disconnects this connection.</summary>
  177. // for future reference, here is how Disconnects work in Mirror.
  178. //
  179. // first, there are two types of disconnects:
  180. // * voluntary: the other end simply disconnected
  181. // * involuntary: server disconnects a client by itself
  182. //
  183. // UNET had special (complex) code to handle both cases differently.
  184. //
  185. // Mirror handles both cases the same way:
  186. // * Disconnect is called from TOP to BOTTOM
  187. // NetworkServer/Client -> NetworkConnection -> Transport.Disconnect()
  188. // * Disconnect is handled from BOTTOM to TOP
  189. // Transport.OnDisconnected -> ...
  190. //
  191. // in other words, calling Disconnect() does no cleanup whatsoever.
  192. // it simply asks the transport to disconnect.
  193. // then later the transport events will do the clean up.
  194. public abstract void Disconnect();
  195. public override string ToString() => $"connection({connectionId})";
  196. // TODO move to server's NetworkConnectionToClient?
  197. internal void AddToObserving(NetworkIdentity netIdentity)
  198. {
  199. observing.Add(netIdentity);
  200. // spawn identity for this conn
  201. NetworkServer.ShowForConnection(netIdentity, this);
  202. }
  203. // TODO move to server's NetworkConnectionToClient?
  204. internal void RemoveFromObserving(NetworkIdentity netIdentity, bool isDestroyed)
  205. {
  206. observing.Remove(netIdentity);
  207. if (!isDestroyed)
  208. {
  209. // hide identity for this conn
  210. NetworkServer.HideForConnection(netIdentity, this);
  211. }
  212. }
  213. // TODO move to server's NetworkConnectionToClient?
  214. internal void RemoveFromObservingsObservers()
  215. {
  216. foreach (NetworkIdentity netIdentity in observing)
  217. {
  218. netIdentity.RemoveObserverInternal(this);
  219. }
  220. observing.Clear();
  221. }
  222. /// <summary>Check if we received a message within the last 'timeout' seconds.</summary>
  223. internal virtual bool IsAlive(float timeout) => Time.time - lastMessageTime < timeout;
  224. internal void AddOwnedObject(NetworkIdentity obj)
  225. {
  226. clientOwnedObjects.Add(obj);
  227. }
  228. internal void RemoveOwnedObject(NetworkIdentity obj)
  229. {
  230. clientOwnedObjects.Remove(obj);
  231. }
  232. internal void DestroyOwnedObjects()
  233. {
  234. // create a copy because the list might be modified when destroying
  235. HashSet<NetworkIdentity> tmp = new HashSet<NetworkIdentity>(clientOwnedObjects);
  236. foreach (NetworkIdentity netIdentity in tmp)
  237. {
  238. if (netIdentity != null)
  239. {
  240. NetworkServer.Destroy(netIdentity.gameObject);
  241. }
  242. }
  243. // clear the hashset because we destroyed them all
  244. clientOwnedObjects.Clear();
  245. }
  246. }
  247. }