Unity教程之-Unity5.1新的网络引擎UNET(五)UNET Network Messages

 

继续上篇文章《Unity教程之-Unity5.1 新的网络引擎UNET Remote Actions》,本篇文章我们来看下UNET Network Messages ,除了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类型:

  • EmptyMessage
  • StringMessage
  • IntegerMessage

发送一条消息有是 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 类没有序列化代码。

好了,本篇unity3d教程关于Unity5.1新的网络引擎UNET Network Messages 到此结束,下篇我们来看下

UNET Multiplayer Lobby