定义可用于在主机(由 hostID 定义)拥有网络事件时获取通知的回调委托。系统会对所有事件类型(NetworkEventType.Nothing 除外)调用该回调。
另请参阅:NetworkEventType
此回调将从 IO 线程调用。如果您通过此回调长时间执行某个操作,它会影响您的 IO 操作性能,因此,您应尽快从此类操作中返回。
using System; using UnityEngine; using UnityEngine.Networking;
public class Test : MonoBehaviour { static int receiveCallbackOld = 0; static int receiveCallbackNew = 0; static int recHostId = -1;
//... public static void ReceiveCallback(int hostId) { ++receiveCallbackNew; //Notify main thread that ReceiveFromHost(hostId, ...) should be called, because there is incoming event waiting to read recHostId = hostId; }
void Start() { GlobalConfig config = new GlobalConfig(); config.NetworkEventAvailable = ReceiveCallback;
//.... }
void Update() { int recConnectionId = 0; int recChannelId = -1; var recArray = new byte[1400]; int recSize = 0; byte error; if (receiveCallbackNew != receiveCallbackOld) { receiveCallbackNew = receiveCallbackOld; var networkEvent = NetworkTransport.ReceiveFromHost(recHostId, out recConnectionId, out recChannelId, recArray, (ushort)recArray.Length, out recSize, out error); Debug.Assert(networkEvent != NetworkEventType.Nothing); } } }