hikalkan / scs

TCP Server/Client Communication and RMI Framework
MIT License
225 stars 112 forks source link

_receiveMemoryStream lenght error #32

Open michaelmnich opened 6 years ago

michaelmnich commented 6 years ago

why always is needed to use

        private static void WriteInt32(byte[] buffer, int startIndex, int number)
        {
            buffer[startIndex] = (byte)((number >> 24) & 0xFF);
            buffer[startIndex + 1] = (byte)((number >> 16) & 0xFF);
            buffer[startIndex + 2] = (byte)((number >> 8) & 0xFF);
            buffer[startIndex + 3] = (byte)((number) & 0xFF);
        }

because of that offset you did soft hard to work wit any other languages. If you made serwer side with your scs lib and client side with java. And you are using simple txt message you must remember to transform every command by that function because simple you will get Exception because:

  var messageLength = ReadInt32(_receiveMemoryStream);
            if (messageLength > MaxMessageLength) //That will be true

I'v made some solution for that soft can be compatible with java.

 private static void WriteInt32(byte[] buffer, int startIndex, int number)
    {
        buffer[startIndex] = (byte)((number >> 24) & 0xFF);
        buffer[startIndex + 1] = (byte)((number >> 16) & 0xFF);
        buffer[startIndex + 2] = (byte)((number >> 8) & 0xFF);
        buffer[startIndex + 3] = (byte)((number) & 0xFF);
    }

    public static byte[] GetBytes(String message) throws UnsupportedEncodingException {

        byte[] serializedMessage = message.getBytes("UTF-8");

       int messageLength = serializedMessage.length;

        //Create a byte array including the length of the message (4 bytes) and serialized message content
        byte[] bytes = new byte[messageLength + 4];
        WriteInt32(bytes, 0, messageLength);
        System.arraycopy(serializedMessage, 0, bytes, 4, messageLength);

        return bytes;
    }

and use it like that:


                String str = "asdsa\n";
                byte[] b = GetBytes(str);
                DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
                outToServer.write(b, 0, b.length);