123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using Unity.Networking.Transport;
- using KairoEngine.Core;
- using Sirenix.OdinInspector;
- namespace KairoEngine.Multiplayer
- {
- [HideMonoScript]
- public class ClientNetMsgController : NetMsgController
- {
- public ClientBehaviour client;
- public NetworkTick networkTick;
-
- private List<NetMsg> sendMsgBuffer = new List<NetMsg>();
- private List<NetMsg> receivedMsgBuffer = new List<NetMsg>();
- private void Start()
- {
- GetNetMessageTypes();
- networkTick.eventStreamName = client.eventStreamName;
- }
- private void OnEnable()
- {
- GenericEvents.StartListening($"{client.eventStreamName}_OnTick", OnTick);
- GenericEvents.StartListening($"{client.eventStreamName}_Connected", StartTickSystem);
- }
- private void OnDisable()
- {
- GenericEvents.StopListening($"{client.eventStreamName}_OnTick", OnTick);
- GenericEvents.StopListening($"{client.eventStreamName}_Connected", StartTickSystem);
- }
- private void StartTickSystem(string text) => networkTick.StartTickSystem();
- public override void ReceiveData(ref DataStreamReader stream, ClientBehaviour client)
- {
- uint tick = stream.ReadUInt();
- uint msgCount = stream.ReadByte();
- for (int i = 0; i < msgCount; i++)
- {
- uint code = stream.ReadByte();
- NetMsg msg = FindWithCode(code).ReceiveMessage(client, ref stream);
- receivedMsgBuffer.Add(msg);
- }
- }
- public override void SendData(uint code, NetMsg netMsg, ClientBehaviour client)
- {
- sendMsgBuffer.Add(netMsg);
- }
- private void OnTick(int tick)
- {
- SendBufferedData();
- ReadBufferedData();
- }
- private void SendBufferedData()
- {
- if(sendMsgBuffer.Count == 0) return;
- Debug.Log("Sending buffered data from client to server");
- DataStreamWriter writer = new DataStreamWriter();
- client.m_Driver.BeginSend(client.m_Connection, out writer);
- writer.WriteUInt((uint)networkTick.tick); // Current Tick Header
- writer.WriteByte((byte)sendMsgBuffer.Count); // Message count Header
- for (int a = 0; a < sendMsgBuffer.Count; a++)
- {
- NetMsg netMsg = sendMsgBuffer[a];
- if(netMsg != null)
- {
- NetMsg typeMsg = FindWithCode(netMsg.code);
- if(typeMsg != null) typeMsg.SendMessage(client, netMsg, ref writer);
- else Debug.LogError($"Could not find NetMsg with code {netMsg.code}");
- }
- }
- client.m_Driver.EndSend(writer);
- sendMsgBuffer.Clear();
- }
- private void ReadBufferedData()
- {
- for (int a = 0; a < receivedMsgBuffer.Count; a++)
- {
- NetMsg msg = receivedMsgBuffer[a];
- msg.ReadMessage(client);
- }
- receivedMsgBuffer.Clear();
- }
- }
- }
|