/// <summary> /// Default parameterless constructor /// </summary> private MsgBase() { MessageType = MessageTypeID.Invalid; }
/// <summary> /// Constructor to force definition of the message type /// </summary> /// <param name="message_type">The message type to associate with the message</param> public MsgBase(MessageTypeID message_type) { MessageType = message_type; }
/// <summary> /// Attempts to receive a message from the provided TCP client /// </summary> /// <param name="client">The client to read the message from</param> /// <returns>A message if found; otherwise null</returns> static public MsgBase ReadMessage(ClientStruct client) { // Check if the client has bytes availble to read // If not, return null if (client.client.Available > 0) { // Read the string StringBuilder sb = new StringBuilder(); char c = '\0'; int colon_count = 0; while ((c != '}' || colon_count > 0) && sb.Length < 10240) { c = (char)client.stream.ReadByte(); sb.Append(c); if (c == '{') { colon_count += 1; } else if (c == '}') { colon_count -= 1; } } string s = sb.ToString(); // Print the string output if (print_output) { Console.WriteLine("Receiving " + s); } // Extract the message type to use in parsing MessageTypeID msg_type = MessageTypeID.Invalid; { // Parse the JSON document JsonDocument msg_doc = JsonDocument.Parse(s); // Pull out the message type, and if successful, extract the message type value if (msg_doc.RootElement.TryGetProperty("MessageType", out JsonElement msg_type_element) && msg_type_element.TryGetInt32(out int msg_type_id_int)) { msg_type = (MessageTypeID)msg_type_id_int; } } // Define the message item MsgBase msg_item; if (type_convert_dict.ContainsKey(msg_type)) { msg_item = (MsgBase)JsonSerializer.Deserialize( s, type_convert_dict[msg_type]); if (msg_item != null && !msg_item.CheckMessage()) { msg_item = null; } } else { msg_item = null; } // Return the parsed message, or null if all failed return(msg_item); } // Return null if no bytes available to read else { return(null); } }