public static uint GetChangeCount(this SyncObject syncObject) { using (NetworkWriterPooled writer = NetworkWriterPool.Get()) { syncObject.OnSerializeDelta(writer); using (NetworkReaderPooled reader = NetworkReaderPool.Get(writer.ToArraySegment())) { return(reader.ReadUInt()); } } }
static void SyncNetworkBehaviour(NetworkBehaviour source, NetworkBehaviour target, bool initialState) { using (NetworkWriterPooled writer = NetworkWriterPool.Get()) { source.OnSerialize(writer, initialState); using (NetworkReaderPooled reader = NetworkReaderPool.Get(writer.ToArraySegment())) { target.OnDeserialize(reader, initialState); } } }
// unpack a message we received public static T UnpackFromByteArray <T>(byte[] data) where T : struct, NetworkMessage { using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(data)) { int msgType = MessagePacking.GetId <T>(); int id = networkReader.ReadUShort(); if (id != msgType) { throw new FormatException($"Invalid message, could not unpack {typeof(T).FullName}"); } return(networkReader.Read <T>()); } }
async Task ReceiveGameBroadcastAsync(UdpClient udpClient) { // only proceed if there is available data in network buffer, or otherwise Receive() will block // average time for UdpClient.Available : 10 us UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync(); using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(udpReceiveResult.Buffer)) { if (networkReader.ReadLong() != secretHandshake) { return; } Response response = networkReader.Read <Response>(); ProcessResponse(response, udpReceiveResult.RemoteEndPoint); } }
public void ReadBytesCountTooBigTest() { // calling ReadBytes with a count bigger than what is in Reader // should throw an exception byte[] bytes = { 0x00, 0x01 }; using (NetworkReaderPooled reader = NetworkReaderPool.Get(bytes)) { try { byte[] result = reader.ReadBytes(bytes, bytes.Length + 1); // BAD: IF WE GOT HERE, THEN NO EXCEPTION WAS THROWN Assert.Fail(); } catch (EndOfStreamException) { // GOOD } } }
async Task ReceiveRequestAsync(UdpClient udpClient) { // only proceed if there is available data in network buffer, or otherwise Receive() will block // average time for UdpClient.Available : 10 us UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync(); using (NetworkReaderPooled networkReader = NetworkReaderPool.Get(udpReceiveResult.Buffer)) { long handshake = networkReader.ReadLong(); if (handshake != secretHandshake) { // message is not for us throw new ProtocolViolationException("Invalid handshake"); } Request request = networkReader.Read <Request>(); ProcessClientRequest(request, udpReceiveResult.RemoteEndPoint); } }