NetworkConnection

This commit is contained in:
Chris Langsenkamp 2019-07-29 03:56:42 -04:00
parent 42f27dbc95
commit 01d144bc62

View File

@ -5,18 +5,65 @@
namespace Mirror
{
/// <summary>
/// A High level network connection. This is used for connections from client-to-server and for connection from server-to-client.
/// <para>A NetworkConnection corresponds to a specific connection for a host in the transport layer. It has a connectionId that is assigned by the transport layer and passed to the Initialize function.</para>
/// <para>A NetworkClient has one NetworkConnection. A NetworkServerSimple manages multiple NetworkConnections. The NetworkServer has multiple "remote" connections and a "local" connection for the local client.</para>
/// <para>The NetworkConnection class provides message sending and handling facilities. For sending data over a network, there are methods to send message objects, byte arrays, and NetworkWriter objects. To handle data arriving from the network, handler functions can be registered for message Ids, byte arrays can be processed by HandleBytes(), and NetworkReader object can be processed by HandleReader().</para>
/// <para>NetworkConnection objects also act as observers for networked objects. When a connection is an observer of a networked object with a NetworkIdentity, then the object will be visible to corresponding client for the connection, and incremental state changes will be sent to the client.</para>
/// <para>NetworkConnection objects can "own" networked game objects. Owned objects will be destroyed on the server by default when the connection is destroyed. A connection owns the player objects created by its client, and other objects with client-authority assigned to the corresponding client.</para>
/// <para>There are many virtual functions on NetworkConnection that allow its behaviour to be customized. NetworkClient and NetworkServer can both be made to instantiate custom classes derived from NetworkConnection by setting their networkConnectionClass member variable.</para>
/// </summary>
public class NetworkConnection : IDisposable
{
public readonly HashSet<NetworkIdentity> visList = new HashSet<NetworkIdentity>();
Dictionary<int, NetworkMessageDelegate> messageHandlers;
/// <summary>
/// Unique identifier for this connection that is assigned by the transport layer.
/// <para>On a server, this Id is unique for every connection on the server. On a client this Id is local to the client, it is not the same as the Id on the server for this connection.</para>
/// <para>Transport layers connections begin at one. So on a client with a single connection to a server, the connectionId of that connection will be one. In NetworkServer, the connectionId of the local connection is zero.</para>
/// <para>Clients do not know their connectionId on the server, and do not know the connectionId of other clients on the server.</para>
/// </summary>
public int connectionId = -1;
/// <summary>
/// Flag that tells if the connection has been marked as "ready" by a client calling ClientScene.Ready().
/// <para>This property is read-only. It is set by the system on the client when ClientScene.Ready() is called, and set by the system on the server when a ready message is received from a client.</para>
/// <para>A client that is ready is sent spawned objects by the server and updates to the state of spawned objects. A client that is not ready is not sent spawned objects.</para>
/// </summary>
public bool isReady;
/// <summary>
/// The IP address / URL / FQDN associated with the connection.
/// </summary>
public string address;
/// <summary>
/// The last time that a message was received on this connection.
/// <para>This includes internal system messages (such as Commands and ClientRpc calls) and user messages.</para>
/// </summary>
public float lastMessageTime;
/// <summary>
/// The NetworkIdentity for this connection.
/// </summary>
public NetworkIdentity playerController { get; internal set; }
/// <summary>
/// A list of the NetworkIdentity objects owned by this connection.
/// <para>This includes the player object for the connection - if it has localPlayerAutority set, and any objects spawned with local authority or set with AssignLocalAuthority. This list is read only.</para>
/// <para>This list can be used to validate messages from clients, to ensure that clients are only trying to control objects that they own.</para>
/// </summary>
public readonly HashSet<uint> clientOwnedObjects = new HashSet<uint>();
/// <summary>
/// Setting this to true will log the contents of network message to the console.
/// <para>Warning: this can be a lot of data and can be very slow. Both incoming and outgoing messages are logged. The format of the logs is:</para>
/// <para>ConnectionSend con:1 bytes:11 msgId:5 FB59D743FD120000000000 ConnectionRecv con:1 bytes:27 msgId:8 14F21000000000016800AC3FE090C240437846403CDDC0BD3B0000</para>
/// <para>Note that these are application-level network messages, not protocol-level packets. There will typically be multiple network messages combined in a single protocol packet.</para>
/// </summary>
public bool logNetworkMessages;
// this is always true for regular connections, false for local
@ -29,10 +76,20 @@ public class NetworkConnection : IDisposable
[EditorBrowsable(EditorBrowsableState.Never), Obsolete("hostId will be removed because it's not needed ever since we removed LLAPI as default. It's always 0 for regular connections and -1 for local connections. Use connection.GetType() == typeof(NetworkConnection) to check if it's a regular or local connection.")]
public int hostId = -1;
/// <summary>
/// Creates a new NetworkConnection with the specified address
/// </summary>
/// <param name="networkAddress"></param>
public NetworkConnection(string networkAddress)
{
address = networkAddress;
}
/// <summary>
/// Creates a new NetworkConnection with the specified address and connectionId
/// </summary>
/// <param name="networkAddress"></param>
/// <param name="networkConnectionId"></param>
public NetworkConnection(string networkAddress, int networkConnectionId)
{
address = networkAddress;
@ -48,6 +105,9 @@ public NetworkConnection(string networkAddress, int networkConnectionId)
Dispose(false);
}
/// <summary>
/// Disposes of this connection, releasing channel buffers that it holds.
/// </summary>
public void Dispose()
{
Dispose(true);
@ -69,6 +129,9 @@ protected virtual void Dispose(bool disposing)
clientOwnedObjects.Clear();
}
/// <summary>
/// Disconnects this connection.
/// </summary>
public void Disconnect()
{
// don't clear address so we can still access it in NetworkManager.OnServerDisconnect
@ -123,6 +186,13 @@ public virtual bool Send(int msgType, MessageBase msg, int channelId = Channels.
return SendBytes(message, channelId);
}
/// <summary>
/// This sends a network message with a message ID on the connection. This message is sent on channel zero, which by default is the reliable channel.
/// </summary>
/// <typeparam name="T">The message type to unregister.</typeparam>
/// <param name="msg"></param>
/// <param name="channelId"></param>
/// <returns></returns>
public virtual bool Send<T>(T msg, int channelId = Channels.DefaultReliable) where T: IMessageBase
{
// pack message and send
@ -209,6 +279,13 @@ internal bool InvokeHandler(int msgType, NetworkReader reader)
return false;
}
/// <summary>
/// This function invokes the registered handler function for a message.
/// <para>Network connections used by the NetworkClient and NetworkServer use this function for handling network messages.</para>
/// </summary>
/// <typeparam name="T">The message type to unregister.</typeparam>
/// <param name="msg"></param>
/// <returns></returns>
public bool InvokeHandler<T>(T msg) where T : IMessageBase
{
int msgType = MessagePacker.GetId<T>();
@ -216,13 +293,18 @@ public bool InvokeHandler<T>(T msg) where T : IMessageBase
return InvokeHandler(msgType, new NetworkReader(data));
}
// handle this message
// note: original HLAPI HandleBytes function handled >1 message in a while loop, but this wasn't necessary
// anymore because NetworkServer/NetworkClient.Update both use while loops to handle >1 data events per
// frame already.
// -> in other words, we always receive 1 message per Receive call, never two.
// -> can be tested easily with a 1000ms send delay and then logging amount received in while loops here
// and in NetworkServer/Client Update. HandleBytes already takes exactly one.
/// <summary>
/// This virtual function allows custom network connection classes to process data from the network before it is passed to the application.
/// <para>
/// note: original HLAPI HandleBytes function handled >1 message in a while loop, but this wasn't necessary
/// anymore because NetworkServer/NetworkClient Update both use while loops to handle >1 data events per
/// frame already.
/// -> in other words, we always receive 1 message per Receive call, never two.
/// -> can be tested easily with a 1000ms send delay and then logging amount received in while loops here
/// and in NetworkServer/Client Update. HandleBytes already takes exactly one.
/// </para>
/// </summary>
/// <param name="buffer"></param>
public virtual void TransportReceive(ArraySegment<byte> buffer)
{
// unpack message
@ -245,6 +327,12 @@ public virtual void TransportReceive(ArraySegment<byte> buffer)
}
}
/// <summary>
/// This virtual function allows custom network connection classes to process data send by the application before it goes to the network transport layer.
/// </summary>
/// <param name="channelId"></param>
/// <param name="bytes"></param>
/// <returns></returns>
public virtual bool TransportSend(int channelId, byte[] bytes)
{
if (Transport.activeTransport.ClientConnected())