??
孙广东 2015.7.12
除了high level facilities 的命令和 RPC 调用,还有可能将原始网络消息进行发送。
还有一类被称为 MessageBase,可以扩展,使可序列化的网络消息类。此类有读/写对象的序列化和反序列化功能。开发人员可以执行这些函数本身,或依赖于通过网络系统自动被创建的代码生成实现。基类看起来像这样:
public abstract class MessageBase { // De-serialize the contents of the reader into this message public virtual void Deserialize(NetworkReader reader) {} // Serialize the contents of this message into the writer public virtual void Serialize(NetworkWriter writer) {} }
有内置message 类为常用的网络messages类型:
发送一条消息有是 Send() 函数, 在 NetworkClient、 NetworkServer 和NetworkConnection 的工作方式相同。他们把消息 Id 和消息对象从 MessageBase 派生。下面的代码显示了如何发送和处理消息,使用的内置message classes之一:
using UnityEngine; using UnityEngine.Networking; using UnityEngine.Networking.NetworkSystem; public class Begin : NetworkBehaviour { const short MyBeginMsg = 1002; NetworkClient m_client; public void SendReadyToBeginMessage(int myId) { var msg = new IntegerMessage(myId); m_client.Send(MyBeginMsg, msg); } public void Init(NetworkClient client) { m_client = client; NetworkServer.RegisterHandler(MyBeginMsg, OnServerReadyToBeginMessage); } void OnServerReadyToBeginMessage(NetworkMessage netMsg) { var beginMessage = netMsg.ReadMessage<IntegerMessage>(); Debug.Log("received OnServerReadyToBeginMessage " + beginMessage.value); } }
声明一个自定义网络message类并 使用它:
using UnityEngine; using UnityEngine.Networking; public class Scores : MonoBehaviour { NetworkClient myClient; public class MyMsgType { public static short Score = MsgType.Highest + 1; }; public class ScoreMessage : MessageBase { public int score; public Vector3 scorePos; public int lives; } public void SendScore(int score, Vector3 scorePos, int lives) { ScoreMessage msg = new ScoreMessage(); msg.score = score; msg.scorePos = scorePos; msg.lives = lives; NetworkServer.SendToAll(MyMsgType.Score, msg); } // Create a client and connect to the server port public void SetupClient() { myClient = new NetworkClient(); myClient.RegisterHandler(MsgType.Connect, OnConnected); myClient.RegisterHandler(MyMsgType.Score, OnScore); myClient.Connect("127.0.0.1", 4444); } public void OnScore(NetworkMessage netMsg) { ScoreMessage msg = netMsg.ReadMessage<ScoreMessage>(); Debug.Log("OnScoreMessage " + msg.score); } public void OnConnected(NetworkMessage netMsg) { Debug.Log("Connected to server"); } }
请注意,此示例中的 ScoreMessage 类没有序列化代码。
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-06 22:13:14