public void CustomPackageTest() { var writer = new NetDataWriter(); _packetProcessor.Write(writer, _samplePacket); var reader = new NetDataReader(writer.CopyData()); SamplePacket readPackage = null; _packetProcessor.SubscribeReusable <SamplePacket>( packet => { readPackage = packet; }); _packetProcessor.ReadAllPackets(reader); Assert.NotNull(readPackage); Assert.IsTrue(AreSame(_samplePacket.EmptyString, readPackage.EmptyString)); Assert.AreEqual(_samplePacket.SomeFloat, readPackage.SomeFloat); Assert.AreEqual(_samplePacket.SomeIntArray, readPackage.SomeIntArray); Assert.IsTrue(AreSame(_samplePacket.SomeString, readPackage.SomeString)); Assert.AreEqual(_samplePacket.SomeVector2, readPackage.SomeVector2); Assert.AreEqual(_samplePacket.SomeVectors, readPackage.SomeVectors); Assert.AreEqual(_samplePacket.SomeEnum, readPackage.SomeEnum); Assert.AreEqual(_samplePacket.TestObj.Value, readPackage.TestObj.Value); Assert.AreEqual(_samplePacket.TestArray, readPackage.TestArray); Assert.AreEqual(_samplePacket.SomeByteArray, readPackage.SomeByteArray); Assert.AreEqual(_samplePacket.SampleClassArray, readPackage.SampleClassArray); }
/* * Create a packet which indicates a protocol violation from clients. */ public static byte[] CreateProtocolError(string msg) { w.Reset(); w.Put((byte)90); w.Put(msg); return(w.CopyData()); }
public void TestThingMessage() { // Test whether the serialization framework supports property inheritance. // ThingMessage.Create derives from CreateMessage which has an Id property. var createThingMessage = new ThingMessages.Create(1, new int[] { }); var writer = new NetDataWriter(); NetPacketProcessor processor = new NetPacketProcessor(); processor.RegisterNestedType <DistributedId>(); processor.Write(writer, createThingMessage); var reader = new NetDataReader(writer.CopyData()); ThingMessages.Create readMessage = null; processor.Subscribe( createMessage => readMessage = createMessage, () => new ThingMessages.Create()); processor.ReadAllPackets(reader); Assert.IsNotNull(readMessage); Assert.AreEqual(new DistributedId(1), readMessage.Id); }
public void TestSocketAddress() { IPEndPoint endPoint = new IPEndPoint(new IPAddress(0), 1); SocketAddress socketAddress = endPoint.Serialize(); var serializedSocketAddress = new SerializedSocketAddress(socketAddress); var packet = new Packet { SerializedSocketAddress = serializedSocketAddress }; var writer = new NetDataWriter(); NetPacketProcessor processor = new NetPacketProcessor(); SerializedSocketAddress.RegisterWith(processor); processor.Write(writer, packet); var reader = new NetDataReader(writer.CopyData()); Packet readPacket = null; processor.Subscribe <Packet>(packet => readPacket = packet, () => new Packet()); processor.ReadAllPackets(reader); Assert.IsNotNull(readPacket); Assert.AreEqual(serializedSocketAddress.SocketAddress, readPacket.SerializedSocketAddress.SocketAddress); }
public void Can_serialize_and_deserialize_entities() { var componentManager = new ComponentManager(); var entityManager = new EntityManager(componentManager); var entityFactory = new EntityFactory(); var serializer = new Serializer(); entityFactory.CreatePlayer(entityManager.Create(), new Vector2(200, 400), 1, PlayerIndex.One, default); entityFactory.CreatePlayer(entityManager.Create(), new Vector2(300, 400), 2, PlayerIndex.Two, default); var state = FullGameState.CreateFullGameState(componentManager, entityManager.Entities, 1, DateTime.UtcNow, DateTime.UtcNow.AddSeconds(1), 1); var writer = new NetDataWriter(); writer.Put(serializer.Serialize(state)); var bytes = writer.CopyData(); var reader = new NetDataReader(bytes); var target = serializer.Deserialize <FullGameState>(reader.GetRemainingBytes()); target.Components.Should() .BeEquivalentTo(state.Components, o => o .Excluding(c => c.Path.EndsWith(nameof(CollisionBody.OldPosition)) || c.Path.EndsWith(nameof(PlayerState.LocalPlayerIndex)) || c.Path.EndsWith(nameof(PlayerState.IsLocal)) ) ); }
public bool ServerSend(long connectionId, byte dataChannel, DeliveryMethod deliveryMethod, NetDataWriter writer) { TransportEventData data = new TransportEventData(); data.type = ENetworkEvent.DataEvent; data.reader = new NetDataReader(writer.CopyData()); serverData.Enqueue(data); return(true); }
public bool ClientSend(byte dataChannel, DeliveryMethod deliveryMethod, NetDataWriter writer) { TransportEventData data = new TransportEventData(); data.type = ENetworkEvent.DataEvent; data.reader = new NetDataReader(writer.CopyData()); clientData.Enqueue(data); return(true); }
public static void Broadcast(MessageType messageType, NetDataWriter netDataWriter) { var data = netDataWriter.CopyData(); netDataWriter.Reset(); netDataWriter.Put((byte)messageType); netDataWriter.Put(data); _server.SendToAll(netDataWriter, DeliveryMethod.ReliableOrdered); }
public byte[] Serialize(NetDataWriter writer) { writer.Put((uint)NetStates.Count); for (int i = 0; i < NetStates.Count; i++) { writer.PutBytesWithLength(NetStates[i]); writer.Put(NetIDs[i]); } return(writer.CopyData()); }
public static void SendMessage(MessageType messageType, NetDataWriter writer) { Debug.Log($"sent {messageType.ToString()}"); var data = writer.CopyData(); writer.Reset(); writer.Put((byte)messageType); writer.Put(data); _client.FirstPeer.Send(writer, DeliveryMethod.ReliableOrdered); }
protected sealed override void OnInitialize() { myPhysics = GetComponent <PhysicsObject>(); light = GetComponent <LightComponent>(); NetworkIdentity networkIdentity = GetComponent <NetworkIdentity>(); Sprite sprite = GetComponent <Sprite>(); if (Network.InstanceType == NetInstanceType.Server) { myPhysics.Body = Physics.CreateCircle(16, 1.0f, new Vector2(16), BodyType.Dynamic); myPhysics.Body.SetRestitution(0.5f); myPhysics.Body.SetFriction(0.0f); //myPhysics.Body.OnCollision += Body_OnCollision; // Test event code. SetV(new Vector2(Random.Next(256, 512), Random.Next(256, 512))); c = new Color(Random.Next(100, 255), Random.Next(100, 255), Random.Next(100, 255)); } else { myPhysics.Enabled = false; } SpriteTexture tex = AssetManager.Get <SpriteTexture>(this, "circle"); ParticleSystem system = GetComponent <ParticleSystem>(); system.Texture = AssetManager.Get <Texture2D>(this, "Smoke"); system.SourceRect = tex.SourceRectangle; networkIdentity.OnSerializeNetworkState += () => { NetDataWriter writer = new NetDataWriter(); writer.Put(sprite.Color.R); writer.Put(sprite.Color.G); writer.Put(sprite.Color.B); writer.Put(sprite.Color.A); return(writer.CopyData()); }; networkIdentity.OnRestoreNetworkState += reader => { c = new Color(reader.GetByte(), reader.GetByte(), reader.GetByte(), reader.GetByte()); sprite.Color = c; light.Color = c; }; sprite.SpriteTexture = tex; sprite.Origin = new Vector2(16, 16); sprite.Color = c; sprite.BlendMode = BlendMode.Transparent; light.Size = new Vector2(400, 400); light.Color = c; light.Intensity = 1.0f; light.Enabled = false; base.OnInitialize(); }
public byte[] SerializeNetworkState(NetDataWriter writer) { writer.Put(Owner.Transform.Position.X); writer.Put(Owner.Transform.Position.Y); writer.Put(curVelocity.X); writer.Put(curVelocity.Y); writer.Put(Owner.Transform.Scale.X); writer.Put(Owner.Transform.Scale.Y); writer.Put(Owner.Transform.Rotation); return(writer.CopyData()); }
public byte[] SerializeMsg <T>(T messageData) { writer.Reset(); writer.Put(typeof(T).Name); if (messageData != null) { serializer.Serialize(writer, messageData); } //Debug.Log("Send Byte[] :" + writer.CopyData().Length); return(writer.CopyData()); }
/// <summary> /// Method invoked when manager receives ping command /// </summary> /// <param name="ping">Ping command</param> private void OnPingCommand(Commands.Ping ping) { var dataWriter = new NetDataWriter(); PacketsProcessor.Write(dataWriter, new Commands.Pong() { Id = ping.Id }); var message = MessagesPool.Instance.GetMessage(dataWriter.Length); message.AddressKey = Key; message.Content.PushBytes(dataWriter.CopyData()); message.Type = DistributedMessageType.Unreliable; BroadcastMessage(message); }
public byte[] Snapshot() { NetDataWriter w = new NetDataWriter(); w.Put(peer.Id); //4 w.Put(score); //2 w.Put(posX); //2 w.Put(posY); //2 w.Put(posZ); //2 w.Put(rotX); //2 w.Put(rotY); //2 w.Put(rotZ); //2 w.Put(health); //4 return(w.CopyData()); //Total: 22bytes }
public static byte[] CreateSnapshot() { NetDataWriter w = new NetDataWriter(); w.Put((byte)3); foreach (Player p in Server.players.Values) { if (p.includeInSnapshot != true) { continue; } w.Put(p.Snapshot()); p.includeInSnapshot = false; } return(w.CopyData()); }
public byte[] TakeFullSnapshot() { NetDataWriter w = new NetDataWriter(); w.Put(peer.Id); //4 w.Put(name.Length); //4 w.Put(name); //Variable w.Put(score); //2 w.Put(posX); //2 w.Put(posY); //2 w.Put(posZ); //2 w.Put(rotX); //2 w.Put(rotY); //2 w.Put(rotZ); //2 w.Put(health); //4 return(w.CopyData()); }
/// <summary> /// Sends loaded command to the master /// </summary> public void SendLoadedCommand() { if (State != SimulationState.Connected) { return; } State = SimulationState.Ready; var dataWriter = new NetDataWriter(); PacketsProcessor.Write(dataWriter, new Commands.Loaded()); var message = MessagesPool.Instance.GetMessage(dataWriter.Length); message.AddressKey = Key; message.Content.PushBytes(dataWriter.CopyData()); message.Type = DistributedMessageType.ReliableOrdered; BroadcastMessage(message); Log.Info($"{GetType().Name} loaded the simulation and has sent loaded command to the master."); }
internal void InstantiateFromBuffer(SpawnedNetObject netObj, NetPeer conn, uint netID, bool isOwner = false) { if (InstanceType != NetInstanceType.Server) { return; } byte[] data = null; byte[] netState = null; byte[] instantiateParams = null; NetDataWriter writer = null; try { if (netObj.NetLogic is INetInstantiatable instantiatable) { writer = NetworkPool.GetWriter(); object[] parameters = instantiatable.InstantiateParameters; foreach (object writeObj in parameters) { writer.Put(NetData.PacketConverters[writeObj.GetType()]); NetData.Write(writeObj.GetType(), writeObj, writer); } instantiateParams = writer.CopyData(); NetworkPool.ReturnWriter(writer); writer = NetworkPool.GetWriter(); data = instantiatable.GetBufferedData(writer); NetworkPool.ReturnWriter(writer); } if (netObj.NetLogic is INetPersistable persist) { writer = NetworkPool.GetWriter(); netState = persist.SerializeNetworkState(writer); NetworkPool.ReturnWriter(writer); } } catch (Exception) { NetworkPool.ReturnWriter(writer); throw; } SendRPC(instantiateMethod, conn, netObj.SpawnableID, conn.GetUniqueID() == netObj.Owner, netObj.NetworkID, netState ?? new byte[0], data ?? new byte[0], instantiateParams ?? new byte[0]); }
/// <summary> /// Broadcast the stop command to the master /// </summary> public void BroadcastStopCommand() { if (State == SimulationState.Stopping || Loader.Instance.Network.CurrentSimulation == null) { return; } Log.Info($"{GetType().Name} broadcasts the simulation stop command."); var dataWriter = new NetDataWriter(); PacketsProcessor.Write(dataWriter, new Commands.Stop { SimulationId = Loader.Instance.Network.CurrentSimulation.Id }); var message = MessagesPool.Instance.GetMessage(dataWriter.Length); message.AddressKey = Key; message.Content.PushBytes(dataWriter.CopyData()); message.Type = DistributedMessageType.ReliableOrdered; BroadcastMessage(message); State = SimulationState.Stopping; }
private void Update() { TimeOfDayCycle(); UpdateRain(); UpdateWet(); UpdateFog(); UpdateSunPosition(); UpdateMoonPosition(); UpdateClouds(); UpdateSunEffect(); UpdatePhysicalSky(); UpdateDamage(); UpdateConfig(); if (Loader.Instance.Network.IsMaster) { var masterManager = Loader.Instance.Network.Master; if (State.Fog != Fog || State.Rain != Rain || State.Wet != Wet || State.Cloud != Cloud || State.Damage != Damage || State.TimeOfDay != CurrentTimeOfDay) { State.Fog = Fog; State.Rain = Rain; State.Wet = Wet; State.Cloud = Cloud; State.Damage = Damage; State.TimeOfDay = CurrentTimeOfDay; var writer = new NetDataWriter(); masterManager.PacketsProcessor.Write(writer, State); var message = MessagesPool.Instance.GetMessage(writer.Length); message.AddressKey = masterManager.Key; message.Content.PushBytes(writer.CopyData()); message.Type = DistributedMessageType.ReliableOrdered; masterManager.BroadcastMessage(message); } } }
public void Instantiate(string type, string owner = "SERVER", object[] parameters = null) { NetDataWriter writer = null; try { if (InstanceType != NetInstanceType.Server) { throw new InvalidOperationException("Attempted to instantiate on a client. Instantiate can only be called on the server."); } if (!spawnables.TryGetValue(type, out Type t)) { throw new Exception("No Spawnable of Type " + type + " found in dictionary."); } object obj = parameters != null ? Activator.CreateInstance(t, parameters) : Activator.CreateInstance(t); INetLogic logic = null; if (obj is INetLogicProxy proxy) { logic = proxy.NetLogic; } else if (obj is INetLogic netLogic) { logic = netLogic; } if (logic == null) { throw new Exception("NetLogic not found."); } SetupNetLogic(logic, owner == "SERVER"); SpawnedNetObjects.TryAdd(logic.ID, new SpawnedNetObject(logic, logic.ID, type, owner)); byte[] returned = null; byte[] netState = null; writer = NetworkPool.GetWriter(); if (parameters != null) { foreach (object writeObj in parameters) { writer.Put(NetData.PacketConverters[writeObj.GetType()]); NetData.Write(writeObj.GetType(), writeObj, writer); } } byte[] paramsData = writer.Length > 0 ? writer.CopyData() : null; NetworkPool.ReturnWriter(writer); if (logic is INetInstantiatable instantiatable) { writer = NetworkPool.GetWriter(); instantiatable.OnNetworkInstantiatedServer(type, owner, writer); NetworkPool.ReturnWriter(writer); writer = NetworkPool.GetWriter(); returned = instantiatable.GetBufferedData(writer); NetworkPool.ReturnWriter(writer); } if (logic is INetPersistable persist) { writer = NetworkPool.GetWriter(); netState = persist.SerializeNetworkState(writer); NetworkPool.ReturnWriter(writer); } foreach (string playerID in Connections.Keys) { SendRPC(instantiateMethod, Connections[playerID], type, playerID == owner, logic.ID, netState ?? new byte[0], returned ?? new byte[0], paramsData ?? new byte[0]); } } catch (Exception e) { NetworkPool.ReturnWriter(writer); LogError(null, new Exception("OOF!", e)); } }
/// <summary> /// Serialize struct to byte array /// </summary> /// <param name="obj">Object to serialize</param> /// <returns>byte array with serialized data</returns> public byte[] Serialize <T>(T obj) where T : class, new() { _writer.Reset(); Serialize(_writer, obj); return(_writer.CopyData()); }