NetworkConnection
NetworkConnection是封装网络连接的HLAPI类。NetworkClient对象具有NetworkConnections,NetworkServers具有多个连接 - 每个客户端都有一个连接。NetworkConnections能够将字节数组或串行化对象作为网络消息发送。
属性
| 属性 | 功能 |
|---|---|
| hostId | 用于此连接的NetworkTransport hostId。 |
| connectionId | NetworkTransport connectionId用于此连接。 |
| isReady | 用于控制是否向其发送状态更新的标志 |
| 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);
}
}
🔚