NetworkManager网络通讯_networkReader/Writer(六)
unet客户端和服务端进行消息发送时可以采用上一节中方法,也可以直接用networkReader/Writer类进行发送
(一)服务端/客户端注册消息
const short k_MyMessage = 100; m_Server.RegisterHandler(k_MyMessage, OnServerMessage);//服务端接收到消息时进行处理
(二)客户端发送消息
void SendMessage() { NetworkWriter writer = new NetworkWriter(); //定义
writer.StartMessage(k_MyMessage);//(一)中消息类型 writer.Write(42); writer.Write(“What is the answer”); //写入消息 writer.FinishMessage(); m_Client.SendWriter(writer, 0); }
(三)服务端进行接收
void OnMyMessage(NetworkMessage netmsg) { Debug.Log(“Got message, size=” + netmsg.reader.Length); var someValue = netmsg.reader.ReadInt32(); var someString = netmsg.reader.ReadString(); Debug.Log(“Message value=” + someValue + “ Message string=‘“ + someString + ”’”); }
注:此例为unity manual中方法