using System;
using System.Collections.Generic;
using System.Text;
namespace UnityEngine.Networking
{
///
/// A High level network connection. This is used for connections from client-to-server and for connection from server-to-client.
/// 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.
/// A NetworkClient has one NetworkConnection. A NetworkServerSimple manages multiple NetworkConnections. The NetworkServer has multiple "remote" connections and a "local" connection for the local client.
/// 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().
/// 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.
/// 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.
/// 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.
///
/*
* wire protocol is a list of : size | msgType | payload
* (short) (variable) (buffer)
*/
[Obsolete("The high level API classes are deprecated and will be removed in the future.")]
public class NetworkConnection : IDisposable
{
ChannelBuffer[] m_Channels;
List m_PlayerControllers = new List();
NetworkMessage m_NetMsg = new NetworkMessage();
HashSet m_VisList = new HashSet();
internal HashSet visList { get { return m_VisList; } }
NetworkWriter m_Writer;
Dictionary m_MessageHandlersDict;
NetworkMessageHandlers m_MessageHandlers;
HashSet m_ClientOwnedObjects;
NetworkMessage m_MessageInfo = new NetworkMessage();
const int k_MaxMessageLogSize = 150;
private NetworkError error;
///
/// Transport level host ID for this connection.
/// This is assigned by the transport layer and passed to the connection instance through the Initialize function.
///
public int hostId = -1;
///
/// Unique identifier for this connection that is assigned by the transport layer.
/// 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.
/// 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.
/// Clients do not know their connectionId on the server, and do not know the connectionId of other clients on the server.
///
public int connectionId = -1;
///
/// Flag that tells if the connection has been marked as "ready" by a client calling ClientScene.Ready().
/// 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.
/// 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.
///
public bool isReady;
///
/// The IP address associated with the connection.
///
public string address;
///
/// The last time that a message was received on this connection.
/// This includes internal system messages (such as Commands and ClientRpc calls) and user messages.
///
public float lastMessageTime;
///
/// The list of players for this connection.
/// In most cases this will be a single player. But, for "Couch Multiplayer" there could be multiple players for a single client. To see the players on your own client see ClientScene.localPlayers list.
///
public List playerControllers { get { return m_PlayerControllers; } }
///
/// A list of the NetworkIdentity objects owned by this connection.
/// 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.
/// This list can be used to validate messages from clients, to ensure that clients are only trying to control objects that they own.
///
/// using UnityEngine;
/// using UnityEngine.Networking;
///
/// public class Handler
/// {
/// static public void HandleTransform(NetworkMessage netMsg)
/// {
/// NetworkInstanceId netId = netMsg.reader.ReadNetworkId();
/// GameObject foundObj = NetworkServer.FindLocalObject(netId);
/// if (foundObj == null)
/// {
/// return;
/// }
/// NetworkTransform foundSync = foundObj.GetComponent<NetworkTransform>();
/// if (foundSync == null)
/// {
/// return;
/// }
/// if (!foundSync.localPlayerAuthority)
/// {
/// return;
/// }
/// if (netMsg.conn.clientOwnedObjects.Contains(netId))
/// {
/// // process message
/// }
/// else
/// {
/// // error
/// }
/// }
/// }
///
///
public HashSet clientOwnedObjects { get { return m_ClientOwnedObjects; } }
///
/// Setting this to true will log the contents of network message to the console.
/// 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:
/// ConnectionSend con:1 bytes:11 msgId:5 FB59D743FD120000000000 ConnectionRecv con:1 bytes:27 msgId:8 14F21000000000016800AC3FE090C240437846403CDDC0BD3B0000
/// 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.
///
public bool logNetworkMessages = false;
///
/// True if the connection is connected to a remote end-point.
/// This applies to NetworkServer and NetworkClient connections. When not connected, the hostID will be -1. When connected, the hostID will be a positive integer.
///
public bool isConnected { get { return hostId != -1; }}
///
/// Structure used to track the number and size of packets of each packets type.
///
public class PacketStat
{
public PacketStat()
{
msgType = 0;
count = 0;
bytes = 0;
}
public PacketStat(PacketStat s)
{
msgType = s.msgType;
count = s.count;
bytes = s.bytes;
}
///
/// The message type these stats are for.
///
public short msgType;
///
/// The total number of messages of this type.
///
public int count;
///
/// Total bytes of all messages of this type.
///
public int bytes;
public override string ToString()
{
return MsgType.MsgTypeToString(msgType) + ": count=" + count + " bytes=" + bytes;
}
}
///
/// The last error associated with this connection.
/// Retrieve the last error that occurred on the connection, this value is set every time an event is received from the NetworkTransport.
/// In the following example, OnServerDisconnect is overridden from NetworkManager:
///
/// using UnityEngine;
/// using UnityEngine.Networking;
///
/// public class ExampleScript : NetworkManager
/// {
/// public override void OnServerDisconnect(NetworkConnection conn)
/// {
/// if (conn.lastError != NetworkError.Ok)
/// {
/// if (LogFilter.logError)
/// {
/// Debug.LogError("ServerDisconnected due to error: " + conn.lastError);
/// }
/// }
/// }
/// }
///
///
public NetworkError lastError { get { return error; } internal set { error = value; } }
Dictionary m_PacketStats = new Dictionary();
internal Dictionary packetStats { get { return m_PacketStats; }}
#if UNITY_EDITOR
static int s_MaxPacketStats = 255;//the same as maximum message types
#endif
///
/// This inializes the internal data structures of a NetworkConnection object, including channel buffers.
/// This is called by NetworkServer and NetworkClient on connection objects, but if used outside of that context, this function should be called before the connection is used.
/// This function can be overriden to perform additional initialization for the connection, but the base class Initialize function should always be called as it is required to setup internal state.
///
/// The host or IP connected to.
/// The transport hostId for the connection.
/// The transport connectionId for the connection.
/// The topology to be used.
public virtual void Initialize(string networkAddress, int networkHostId, int networkConnectionId, HostTopology hostTopology)
{
m_Writer = new NetworkWriter();
address = networkAddress;
hostId = networkHostId;
connectionId = networkConnectionId;
int numChannels = hostTopology.DefaultConfig.ChannelCount;
int packetSize = hostTopology.DefaultConfig.PacketSize;
if ((hostTopology.DefaultConfig.UsePlatformSpecificProtocols) && (UnityEngine.Application.platform != RuntimePlatform.PS4))
throw new ArgumentOutOfRangeException("Platform specific protocols are not supported on this platform");
m_Channels = new ChannelBuffer[numChannels];
for (int i = 0; i < numChannels; i++)
{
var qos = hostTopology.DefaultConfig.Channels[i];
int actualPacketSize = packetSize;
if (qos.QOS == QosType.ReliableFragmented || qos.QOS == QosType.UnreliableFragmented)
{
actualPacketSize = hostTopology.DefaultConfig.FragmentSize * 128;
}
m_Channels[i] = new ChannelBuffer(this, actualPacketSize, (byte)i, IsReliableQoS(qos.QOS), IsSequencedQoS(qos.QOS));
}
}
// Track whether Dispose has been called.
bool m_Disposed;
~NetworkConnection()
{
Dispose(false);
}
///
/// Disposes of this connection, releasing channel buffers that it holds.
///
public void Dispose()
{
Dispose(true);
// Take yourself off the Finalization queue
// to prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!m_Disposed && m_Channels != null)
{
for (int i = 0; i < m_Channels.Length; i++)
{
m_Channels[i].Dispose();
}
}
m_Channels = null;
if (m_ClientOwnedObjects != null)
{
foreach (var netId in m_ClientOwnedObjects)
{
var obj = NetworkServer.FindLocalObject(netId);
if (obj != null)
{
obj.GetComponent().ClearClientOwner();
}
}
}
m_ClientOwnedObjects = null;
m_Disposed = true;
}
static bool IsSequencedQoS(QosType qos)
{
return (qos == QosType.ReliableSequenced || qos == QosType.UnreliableSequenced);
}
static bool IsReliableQoS(QosType qos)
{
return (qos == QosType.Reliable || qos == QosType.ReliableFragmented || qos == QosType.ReliableSequenced || qos == QosType.ReliableStateUpdate);
}
///
/// This sets an option on the network channel.
/// Channel options are usually advanced tuning parameters.
///
/// The channel the option will be set on.
/// The option to set.
/// The value for the option.
/// True if the option was set.
public bool SetChannelOption(int channelId, ChannelOption option, int value)
{
if (m_Channels == null)
return false;
if (channelId < 0 || channelId >= m_Channels.Length)
return false;
return m_Channels[channelId].SetOption(option, value);
}
public NetworkConnection()
{
m_Writer = new NetworkWriter();
}
///
/// Disconnects this connection.
///
public void Disconnect()
{
address = "";
isReady = false;
ClientScene.HandleClientDisconnect(this);
if (hostId == -1)
{
return;
}
byte error;
NetworkManager.activeTransport.Disconnect(hostId, connectionId, out error);
RemoveObservers();
}
internal void SetHandlers(NetworkMessageHandlers handlers)
{
m_MessageHandlers = handlers;
m_MessageHandlersDict = handlers.GetHandlers();
}
///
/// This function checks if there is a message handler registered for the message ID.
/// This is usually not required, as InvokeHandler handles message IDs without handlers.
///
/// The message ID of the handler to look for.
/// True if a handler function was found.
public bool CheckHandler(short msgType)
{
return m_MessageHandlersDict.ContainsKey(msgType);
}
///
/// This function invokes the registered handler function for a message, without any message data.
/// This is useful to invoke handlers that dont have any additional data, such as the handlers for MsgType.Connect.
///
/// The message ID of the handler to invoke.
/// True if a handler function was found and invoked.
public bool InvokeHandlerNoData(short msgType)
{
return InvokeHandler(msgType, null, 0);
}
///
/// This function invokes the registered handler function for a message.
/// Network connections used by the NetworkClient and NetworkServer use this function for handling network messages.
///
/// The message type of the handler to use.
/// The stream to read the contents of the message from.
/// The channel that the message arrived on.
/// True if a handler function was found and invoked.
public bool InvokeHandler(short msgType, NetworkReader reader, int channelId)
{
if (m_MessageHandlersDict.ContainsKey(msgType))
{
m_MessageInfo.msgType = msgType;
m_MessageInfo.conn = this;
m_MessageInfo.reader = reader;
m_MessageInfo.channelId = channelId;
NetworkMessageDelegate msgDelegate = m_MessageHandlersDict[msgType];
if (msgDelegate == null)
{
if (LogFilter.logError) { Debug.LogError("NetworkConnection InvokeHandler no handler for " + msgType); }
return false;
}
msgDelegate(m_MessageInfo);
return true;
}
return false;
}
///
/// This function invokes the registered handler function for a message.
/// Network connections used by the NetworkClient and NetworkServer use this function for handling network messages.
///
/// The message object to process.
/// True if a handler function was found and invoked.
public bool InvokeHandler(NetworkMessage netMsg)
{
if (m_MessageHandlersDict.ContainsKey(netMsg.msgType))
{
NetworkMessageDelegate msgDelegate = m_MessageHandlersDict[netMsg.msgType];
msgDelegate(netMsg);
return true;
}
return false;
}
internal void HandleFragment(NetworkReader reader, int channelId)
{
if (channelId < 0 || channelId >= m_Channels.Length)
{
return;
}
var channel = m_Channels[channelId];
if (channel.HandleFragment(reader))
{
NetworkReader msgReader = new NetworkReader(channel.fragmentBuffer.AsArraySegment().Array);
msgReader.ReadInt16(); // size
short msgType = msgReader.ReadInt16();
InvokeHandler(msgType, msgReader, channelId);
}
}
///
/// This registers a handler function for a message Id.
///
/// The message ID to register.
/// The handler function to register.
public void RegisterHandler(short msgType, NetworkMessageDelegate handler)
{
m_MessageHandlers.RegisterHandler(msgType, handler);
}
///
/// This removes the handler registered for a message Id.
///
/// The message ID to unregister.
public void UnregisterHandler(short msgType)
{
m_MessageHandlers.UnregisterHandler(msgType);
}
internal void SetPlayerController(PlayerController player)
{
while (player.playerControllerId >= m_PlayerControllers.Count)
{
m_PlayerControllers.Add(new PlayerController());
}
m_PlayerControllers[player.playerControllerId] = player;
}
internal void RemovePlayerController(short playerControllerId)
{
int count = m_PlayerControllers.Count;
while (count >= 0)
{
if (playerControllerId == count && playerControllerId == m_PlayerControllers[count].playerControllerId)
{
m_PlayerControllers[count] = new PlayerController();
return;
}
count -= 1;
}
if (LogFilter.logError) { Debug.LogError("RemovePlayer player at playerControllerId " + playerControllerId + " not found"); }
}
// Get player controller from connection's list
internal bool GetPlayerController(short playerControllerId, out PlayerController playerController)
{
playerController = null;
if (playerControllers.Count > 0)
{
for (int i = 0; i < playerControllers.Count; i++)
{
if (playerControllers[i].IsValid && playerControllers[i].playerControllerId == playerControllerId)
{
playerController = playerControllers[i];
return true;
}
}
return false;
}
return false;
}
///
/// This causes the channels of the network connection to flush their data to the transport layer.
/// This is called automatically by connections used by NetworkServer and NetworkClient, but can be called manually for connections used in other contexts.
///
public void FlushChannels()
{
if (m_Channels == null)
{
return;
}
for (int channelId = 0; channelId < m_Channels.Length; channelId++)
{
m_Channels[channelId].CheckInternalBuffer();
}
}
///
/// The maximum time in seconds that messages are buffered before being sent.
/// If this is set to zero, then there will be no buffering of messages before they are sent to the transport layer. This may reduce latency but can lead to packet queue overflow issues if many small packets are being sent.
///
/// Time in seconds.
public void SetMaxDelay(float seconds)
{
if (m_Channels == null)
{
return;
}
for (int channelId = 0; channelId < m_Channels.Length; channelId++)
{
m_Channels[channelId].maxDelay = seconds;
}
}
///
/// 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.
///
/// The ID of the message to send.
/// The message to send.
/// True if the message was sent.
public virtual bool Send(short msgType, MessageBase msg)
{
return SendByChannel(msgType, msg, Channels.DefaultReliable);
}
///
/// This sends a network message with a message ID on the connection. This message is sent on channel one, which by default is the unreliable channel.
///
/// The message ID to send.
/// The message to send.
/// True if the message was sent.
public virtual bool SendUnreliable(short msgType, MessageBase msg)
{
return SendByChannel(msgType, msg, Channels.DefaultUnreliable);
}
///
/// This sends a network message on the connection using a specific transport layer channel.
///
/// The message ID to send.
/// The message to send.
/// The transport layer channel to send on.
/// True if the message was sent.
public virtual bool SendByChannel(short msgType, MessageBase msg, int channelId)
{
m_Writer.StartMessage(msgType);
msg.Serialize(m_Writer);
m_Writer.FinishMessage();
return SendWriter(m_Writer, channelId);
}
///
/// This sends an array of bytes on the connection.
///
/// The array of data to be sent.
/// The number of bytes in the array to be sent.
/// The transport channel to send on.
/// Success if data was sent.
public virtual bool SendBytes(byte[] bytes, int numBytes, int channelId)
{
if (logNetworkMessages)
{
LogSend(bytes);
}
return CheckChannel(channelId) && m_Channels[channelId].SendBytes(bytes, numBytes);
}
///
/// This sends the contents of a NetworkWriter object on the connection.
/// The example below constructs a writer and sends it on a connection.
///
/// using UnityEngine;
/// using UnityEngine.Networking;
///
/// public class ExampleScript : MonoBehaviour
/// {
/// public bool Send(short msgType, MessageBase msg, NetworkConnection conn)
/// {
/// NetworkWriter writer = new NetworkWriter();
/// writer.StartMessage(msgType);
/// msg.Serialize(writer);
/// writer.FinishMessage();
/// return conn.SendWriter(writer, Channels.DefaultReliable);
/// }
/// }
///
///
/// A writer object containing data to send.
/// The transport channel to send on.
/// True if the data was sent.
public virtual bool SendWriter(NetworkWriter writer, int channelId)
{
if (logNetworkMessages)
{
LogSend(writer.ToArray());
}
return CheckChannel(channelId) && m_Channels[channelId].SendWriter(writer);
}
void LogSend(byte[] bytes)
{
NetworkReader reader = new NetworkReader(bytes);
var msgSize = reader.ReadUInt16();
var msgId = reader.ReadUInt16();
const int k_PayloadStartPosition = 4;
StringBuilder msg = new StringBuilder();
for (int i = k_PayloadStartPosition; i < k_PayloadStartPosition + msgSize; i++)
{
msg.AppendFormat("{0:X2}", bytes[i]);
if (i > k_MaxMessageLogSize) break;
}
Debug.Log("ConnectionSend con:" + connectionId + " bytes:" + msgSize + " msgId:" + msgId + " " + msg);
}
bool CheckChannel(int channelId)
{
if (m_Channels == null)
{
if (LogFilter.logWarn) { Debug.LogWarning("Channels not initialized sending on id '" + channelId); }
return false;
}
if (channelId < 0 || channelId >= m_Channels.Length)
{
if (LogFilter.logError) { Debug.LogError("Invalid channel when sending buffered data, '" + channelId + "'. Current channel count is " + m_Channels.Length); }
return false;
}
return true;
}
///
/// Resets the statistics that are returned from NetworkClient.GetConnectionStats().
///
public void ResetStats()
{
#if UNITY_EDITOR
for (short i = 0; i < s_MaxPacketStats; i++)
{
if (m_PacketStats.ContainsKey(i))
{
var value = m_PacketStats[i];
value.count = 0;
value.bytes = 0;
NetworkManager.activeTransport.SetPacketStat(0, i, 0, 0);
NetworkManager.activeTransport.SetPacketStat(1, i, 0, 0);
}
}
#endif
}
///
/// This makes the connection process the data contained in the buffer, and call handler functions.
/// The data is assumed to have come from the network, and contains network messages.
/// This function is used by network connections when they receive data.
///
/// Data to process.
/// Size of the data to process.
/// Channel the data was recieved on.
protected void HandleBytes(
byte[] buffer,
int receivedSize,
int channelId)
{
// build the stream form the buffer passed in
NetworkReader reader = new NetworkReader(buffer);
HandleReader(reader, receivedSize, channelId);
}
///
/// This makes the connection process the data contained in the stream, and call handler functions.
/// The data in the stream is assumed to have come from the network, and contains network messages.
/// This function is used by network connections when they receive data.
///
/// Stream that contains data.
/// Size of the data.
/// Channel the data was received on.
protected void HandleReader(
NetworkReader reader,
int receivedSize,
int channelId)
{
// read until size is reached.
// NOTE: stream.Capacity is 1300, NOT the size of the available data
while (reader.Position < receivedSize)
{
// the reader passed to user code has a copy of bytes from the real stream. user code never touches the real stream.
// this ensures it can never get out of sync if user code reads less or more than the real amount.
ushort sz = reader.ReadUInt16();
short msgType = reader.ReadInt16();
// Bail out here if we're about to read beyond the recieved size of the buffer
// This could be a sign of an attack which could cause us to behave unexpectedly by reading old data
if (reader.Position + sz > receivedSize )
{
if (LogFilter.logError)
{
Debug.LogError("Declared packet size larger than recieved size, possible corruption or attack");
}
break;
}
// create a reader just for this message
//TODO: Allocation!!
byte[] msgBuffer = reader.ReadBytes(sz);
NetworkReader msgReader = new NetworkReader(msgBuffer);
if (logNetworkMessages)
{
StringBuilder msg = new StringBuilder();
for (int i = 0; i < sz; i++)
{
msg.AppendFormat("{0:X2}", msgBuffer[i]);
if (i > k_MaxMessageLogSize) break;
}
Debug.Log("ConnectionRecv con:" + connectionId + " bytes:" + sz + " msgId:" + msgType + " " + msg);
}
NetworkMessageDelegate msgDelegate = null;
if (m_MessageHandlersDict.ContainsKey(msgType))
{
msgDelegate = m_MessageHandlersDict[msgType];
}
if (msgDelegate != null)
{
m_NetMsg.msgType = msgType;
m_NetMsg.reader = msgReader;
m_NetMsg.conn = this;
m_NetMsg.channelId = channelId;
msgDelegate(m_NetMsg);
lastMessageTime = Time.time;
#if UNITY_EDITOR
Profiler.IncrementStatIncoming(MsgType.HLAPIMsg);
if (msgType > MsgType.Highest)
{
Profiler.IncrementStatIncoming(MsgType.UserMessage, msgType + ":" + msgType.GetType().Name);
}
#endif
#if UNITY_EDITOR
if (m_PacketStats.ContainsKey(msgType))
{
PacketStat stat = m_PacketStats[msgType];
stat.count += 1;
stat.bytes += sz;
}
else
{
PacketStat stat = new PacketStat();
stat.msgType = msgType;
stat.count += 1;
stat.bytes += sz;
m_PacketStats[msgType] = stat;
}
#endif
}
else
{
//NOTE: this throws away the rest of the buffer. Need moar error codes
if (LogFilter.logError) { Debug.LogError("Unknown message ID " + msgType + " connId:" + connectionId); }
break;
}
}
}
///
/// Get statistics for outgoing traffic.
///
/// Number of messages sent.
/// Number of messages currently buffered for sending.
/// Number of bytes sent.
/// How many messages were buffered in the last second.
public virtual void GetStatsOut(out int numMsgs, out int numBufferedMsgs, out int numBytes, out int lastBufferedPerSecond)
{
numMsgs = 0;
numBufferedMsgs = 0;
numBytes = 0;
lastBufferedPerSecond = 0;
for (int channelId = 0; channelId < m_Channels.Length; channelId++)
{
var channel = m_Channels[channelId];
numMsgs += channel.numMsgsOut;
numBufferedMsgs += channel.numBufferedMsgsOut;
numBytes += channel.numBytesOut;
lastBufferedPerSecond += channel.lastBufferedPerSecond;
}
}
///
/// Get statistics for incoming traffic.
///
/// Number of messages received.
/// Number of bytes received.
public virtual void GetStatsIn(out int numMsgs, out int numBytes)
{
numMsgs = 0;
numBytes = 0;
for (int channelId = 0; channelId < m_Channels.Length; channelId++)
{
var channel = m_Channels[channelId];
numMsgs += channel.numMsgsIn;
numBytes += channel.numBytesIn;
}
}
///
/// Returns a string representation of the NetworkConnection object state.
///
///
public override string ToString()
{
return string.Format("hostId: {0} connectionId: {1} isReady: {2} channel count: {3}", hostId, connectionId, isReady, (m_Channels != null ? m_Channels.Length : 0));
}
internal void AddToVisList(NetworkIdentity uv)
{
m_VisList.Add(uv);
// spawn uv for this conn
NetworkServer.ShowForConnection(uv, this);
}
internal void RemoveFromVisList(NetworkIdentity uv, bool isDestroyed)
{
m_VisList.Remove(uv);
if (!isDestroyed)
{
// hide uv for this conn
NetworkServer.HideForConnection(uv, this);
}
}
internal void RemoveObservers()
{
foreach (var uv in m_VisList)
{
uv.RemoveObserverInternal(this);
}
m_VisList.Clear();
}
///
/// This virtual function allows custom network connection classes to process data from the network before it is passed to the application.
/// The default implementation of this function calls HandleBytes() on the received data. Custom implmentations can also use HandleBytes(), but can pass modified versions of the data received or other data.
/// This example logs the data received to the console, then passes it to HandleBytes.
///
/// using UnityEngine;
/// using UnityEngine.Networking;
/// using System;
/// using System.Text;
/// public class DebugConnection : NetworkConnection
/// {
/// public override void TransportReceive(byte[] bytes, int numBytes, int channelId)
/// {
/// StringBuilder msg = new StringBuilder();
/// for (int i = 0; i < numBytes; i++) {
/// {
/// var s = String.Format("{0:X2}", bytes[i]);
/// msg.Append(s);
/// if (i > 50) break;
/// }
/// UnityEngine.Debug.LogError("TransportReceive h:" + hostId + " con:" + connectionId + " bytes:" + numBytes + " " + msg);
/// HandleBytes(bytes, numBytes, channelId);
/// }
/// }
///
/// Other uses for this function could be data compression or data encryption.
/// Custom network connection classes are used by setting NetworkServer.NetworkConnectionClass and NetworkClient.NetworkConnectionClass.
///
/// using UnityEngine;
/// using UnityEngine.Networking;
///
/// public class SpaceManager : NetworkManager
/// {
/// void Start()
/// {
/// NetworkServer.networkConnectionClass = typeof(DebugConnection);
/// NetworkClient.networkConnectionClass = typeof(DebugConnection);
/// }
/// }
///
///
/// The data recieved.
/// The size of the data recieved.
/// The channel that the data was received on.
public virtual void TransportReceive(byte[] bytes, int numBytes, int channelId)
{
HandleBytes(bytes, numBytes, channelId);
}
[Obsolete("TransportRecieve has been deprecated. Use TransportReceive instead.", false)]
public virtual void TransportRecieve(byte[] bytes, int numBytes, int channelId)
{
TransportReceive(bytes, numBytes, channelId);
}
///
/// This virtual function allows custom network connection classes to process data send by the application before it goes to the network transport layer.
/// The default implementation of this function calls NetworkTransport.Send() with the supplied data, but custom implementations can pass modified versions of the data. This example logs the sent data to the console:
///
/// using UnityEngine;
/// using UnityEngine.Networking;
/// using System;
/// using System.Text;
///
/// class DebugConnection : NetworkConnection
/// {
/// public override bool TransportSend(byte[] bytes, int numBytes, int channelId, out byte error)
/// {
/// StringBuilder msg = new StringBuilder();
/// for (int i = 0; i < numBytes; i++)
/// {
/// var s = String.Format("{0:X2}", bytes[i]);
/// msg.Append(s);
/// if (i > 50) break;
/// }
/// UnityEngine.Debug.LogError("TransportSend h:" + hostId + " con:" + connectionId + " bytes:" + numBytes + " " + msg);
/// return NetworkTransport.Send(hostId, connectionId, channelId, bytes, numBytes, out error);
/// }
/// }
///
/// Other uses for this function could be data compression or data encryption.
/// Custom network connection classes are used by setting NetworkServer.NetworkConnectionClass and NetworkClient.NetworkConnectionClass.
///
/// using UnityEngine;
/// using UnityEngine.Networking;
///
/// public class SpaceManager : NetworkManager
/// {
/// void Start()
/// {
/// NetworkServer.networkConnectionClass = typeof(DebugConnection);
/// NetworkClient.networkConnectionClass = typeof(DebugConnection);
/// }
/// }
///
///
/// Data to send.
/// Size of data to send.
/// Channel to send data on.
/// Error code for send.
/// True if data was sent.
public virtual bool TransportSend(byte[] bytes, int numBytes, int channelId, out byte error)
{
return NetworkManager.activeTransport.Send(hostId, connectionId, channelId, bytes, numBytes, out error);
}
internal void AddOwnedObject(NetworkIdentity obj)
{
if (m_ClientOwnedObjects == null)
{
m_ClientOwnedObjects = new HashSet();
}
m_ClientOwnedObjects.Add(obj.netId);
}
internal void RemoveOwnedObject(NetworkIdentity obj)
{
if (m_ClientOwnedObjects == null)
{
return;
}
m_ClientOwnedObjects.Remove(obj.netId);
}
internal static void OnFragment(NetworkMessage netMsg)
{
netMsg.conn.HandleFragment(netMsg.reader, netMsg.channelId);
}
}
}