1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- using System;
- using UnityEngine;
- using Unity.Collections;
- using Unity.Netcode;
- //自定义带名称的消息处理
- public class CustomNamedMessageHandler : NetworkBehaviour
- {
- //类似于消息头
- [Tooltip("用于消息处理的标志")]
- public string MessageName = "CustomNamedMessage";
- public override void OnNetworkSpawn()
- {
- //注册带消息的处理回调,此处是ReceiveMessage方法
- //此处是与CustomUnnamedMessageHandler不同的地方。CustomUnnamedMessageHandler使用如下方式注册
- //NetworkManager.CustomMessagingManager.OnUnnamedMessage += ReceiveMessage;
- NetworkManager.CustomMessagingManager.RegisterNamedMessageHandler(MessageName, ReceiveMessage);
- if(IsServer)
- {
- NetworkManager.OnClientConnectedCallback += OnClientConnectedCallback;
- }
- else
- {
- //测试,客户端发送一个Guid
- SendMessage(Guid.NewGuid());
- }
- }
- private void OnClientConnectedCallback(ulong obj)
- {
- SendMessage(Guid.NewGuid());
- }
- public override void OnNetworkDespawn()
- {
- NetworkManager.CustomMessagingManager.UnregisterNamedMessageHandler(MessageName);
- NetworkManager.OnClientConnectedCallback -= OnClientConnectedCallback;
- }
- //收到消息
- private void ReceiveMessage(ulong senderId, FastBufferReader messagePayload)
- {
- //处理接收的数据,用ForceNetworkSerializeByMemcpy进行序列化和反序列化,此处消息是个Guid
- var receivedMessageContent = new ForceNetworkSerializeByMemcpy<Guid>(new Guid());
- messagePayload.ReadValueSafe(out receivedMessageContent);
- if(IsServer)
- {
- Debug.Log($"Sever received GUID ({receivedMessageContent.Value}) from client ({senderId})");
- }
- else
- {
- Debug.Log($"Client received GUID ({receivedMessageContent.Value}) from the server.");
- }
- }
- //发送自定义消息
- public void SendMessage(Guid inGameIdentifier)
- {
- var messageContent = new ForceNetworkSerializeByMemcpy<Guid>(inGameIdentifier);
- var writer = new FastBufferWriter(1100, Allocator.Temp);
- var customMessagingManager = NetworkManager.CustomMessagingManager;
- using(writer)
- {
- //写入消息
- writer.WriteValueSafe(messageContent);
- if(IsServer)
- {
- //发送给所有客户端,某个MessageName的消息处理器
- customMessagingManager.SendNamedMessageToAll(MessageName, writer);
- }
- else
- {
- //发送给某个客户端
- customMessagingManager.SendNamedMessage(MessageName, NetworkManager.ServerClientId, writer);
- }
- }
- }
- }
|