public static byte[] EncodeMessage(string message)
{
try
{
// Convert the string message to a byte array
byte[] messageBytes = System.Text.Encoding.UTF8.GetBytes(message);
// Write the message length as a 4-byte integer followed by the message data
byte[] lengthBytes = BitConverter.GetBytes(messageBytes.Length);
byte[] sendBuffer = new byte[lengthBytes.Length + messageBytes.Length];
Array.Copy(lengthBytes, sendBuffer, lengthBytes.Length);
Array.Copy(messageBytes, 0, sendBuffer, lengthBytes.Length, messageBytes.Length);
return sendBuffer;
}
catch (EncoderFallbackException ex)
{
// Handle encoding error (e.g., log, throw, or return a default value)
Console.WriteLine($"Error encoding message: {ex.Message}");
return null; // or throw an exception or return a default value
}
catch (Exception ex)
{
return null;
}
}
public static string DecodeMessage(byte[] data)
{
try
{
// Read the 4-byte header to get the length of the message
byte[] lengthBytes = new byte[4];
Debug.WriteLine(data.Length.ToString());
Array.Copy(data, lengthBytes, lengthBytes.Length);
int messageLength = BitConverter.ToInt32(lengthBytes, 0);
// Read the message data into a byte array
byte[] messageData = new byte[messageLength];
Array.Copy(data, lengthBytes.Length, messageData, 0, messageLength);
// Convert the message data to a string
string message = System.Text.Encoding.UTF8.GetString(messageData);
return message;
}
catch (Exception ex)
{
return null;
}
}
I got out of memory exception in DecodeMessage function on this line int messageLength = BitConverter.ToInt32(lengthBytes, 0). overall when the messageLength changes (like 5762781 something like it) it gives out of memory exception other wise (like 4561 etc. then it is working fine no issue). what am I doing wrong here?
i tried the Endianness too but that didn't work.