Version: 5.6
NetworkClient
NetworkDiscovery

NetworkConnection

NetworkConnection is a HLAPI class that encapsulates a network connection. NetworkClient objects have a NetworkConnections, and NetworkServers have multiple connections - one from each client. NetworkConnections have the ability to send byte arrays, or serialized objects as network messages.

属性

属性: 功能:
hostId The NetworkTransport hostId for this connection.
connectionId The NetworkTransport connectionId for this connection.
isReady Flag to control whether state updates are sent to this
lastMessageTime 在此连接上收到消息的最后时间。
address 此连接所连接到的端点的 IP 地址。
playerControllers 已使用 AddPlayer() 添加的玩家的集合。
clientOwnedObjects 此连接有授权的对象的集合。

NetworkConnection 类包含当数据发送到传输层或者从传输层接收数据时调用的虚拟函数。这些函数允许专用版本的 NetworkConnection 检查或修改此数据,甚至将数据路由到不同源。下面显示了这些函数,包括默认行为:

public virtual void TransportRecieve(byte[] bytes, int numBytes, int channelId)
{
    HandleBytes(bytes, numBytes, channelId);
}

public virtual bool TransportSend(byte[] bytes, int numBytes, int channelId, out byte error)
{
    return NetworkTransport.Send(hostId, connectionId, channelId, bytes, numBytes, out error);
} 

这些函数的一个用例是记录传入和传出数据包的内容。以下是派生自 NetworkConnection 的 DebugConnection 类的示例,此类用于将数据包的前 50 字节记录到控制台。要使用这样的类,请在 NetworkClient 或 NetworkServer 上调用 SetNetworkConnectionClass() 函数。

class DebugConnection : NetworkConnection
{
    public override void TransportRecieve(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.Log("TransportRecieve h:" + hostId + " con:" + connectionId + " bytes:" + numBytes + " " + msg);

        HandleBytes(bytes, numBytes, channelId);
    }

    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.Log("TransportSend    h:" + hostId + " con:" + connectionId + " bytes:" + numBytes + " " + msg);

        return NetworkTransport.Send(hostId, connectionId, channelId, bytes, numBytes, out error);
    }
}
NetworkClient
NetworkDiscovery
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961