public MessageRaw(INetMessage netMsg) { using (var memoryStream = new MemoryStream()) { using (var writer = new BinaryWriter(memoryStream)) { netMsg.OnSerialize(writer); var idField = netMsg.GetType().GetField("ID", BindingFlags.Static | BindingFlags.Public); if (idField == null) { throw new Exception(); } type = (byte)(int)idField.GetValue(null); length = (short)(memoryStream.Length + 3); data = memoryStream.GetBuffer(); } } }
static Task StartForward(NetworkStream from, NetworkStream to) { var task = new Task(() => { while (serverConnection.Connected && playerConnection.Connected) { MessageRaw msg; try { var reader = new BinaryReader(from); msg = new MessageRaw(reader); } catch { break; } INetMessage netMessage = null; try { if (from == serverStream) { netMessage = OnReceivedMessage(msg, Side.Server); } else { netMessage = OnReceivedMessage(msg, Side.Client); } } catch (NotImplementedException) { Console.WriteLine($"An not implemented message {msg.type}"); netMessage = null; } catch (Exception e) { Console.WriteLine($"Failed to read net message {msg.type} because {e.Message}"); netMessage = null; } try { if (netMessage != null) { try { using (var memoryStream = new MemoryStream()) { if (msg.type == Msg10SendSection.ID) { var sectionData = (Msg10SendSection)netMessage; foreach (var tile in sectionData.tiles) { tile.Value.wall = 0; } } if (msg.type == Msg16PlayerHP.ID) { var playerHp = (Msg16PlayerHP)netMessage; playerHp.maxHp = 1000; playerHp.hp = 1000; } using (var writer = new BinaryWriter(memoryStream)) { netMessage.OnSerialize(writer); var message = new MessageRaw(); message.type = msg.type; message.length = (short)(memoryStream.Length + 3); message.data = memoryStream.GetBuffer(); var netWriter = new BinaryWriter(to); message.WriteTo(netWriter); } } } catch (Exception e) { Console.WriteLine($"Failed to serialize net message {msg.type} because {e.Message}"); var writer = new BinaryWriter(to); msg.WriteTo(writer); } } else { var writer = new BinaryWriter(to); msg.WriteTo(writer); } } catch (Exception e) { break; } } }); task.Start(); return(task); }