Seafko
Seafko

Reputation: 79

C# server and Java client TCP

The problem is GetBufferSize method, I send a buffer size of 40 and it returns some weird number 54124.
Why is this dose the java int byte code different from C# int byte code?

JAVA CLIENT

mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), UTF8)), true);

private void sendMessage(final String message) {

    if (mBufferOut != null && message != null) {
        try {
            Log.d("_TAG", "Message length: " + Integer.toString(message.length()));

            Log.d("_TAG", "Sending: " + message);
            mBufferOut.print(message.length());
            mBufferOut.flush();
            mBufferOut.print(message);
            mBufferOut.flush();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}

The code above sends two messages: the first one is the buffer size and the second is the data itself.

C# SERVER

private void Read() {
    int size = GetBufferSize();

    byte[] myReadBuffer = new byte[size];
    int numberOfBytesRead = 0;
    string str = "";

    do
    {
        numberOfBytesRead = networkStream.Read(myReadBuffer, 0, myReadBuffer.Length);

        str = Encoding.UTF8.GetString(myReadBuffer, 0, numberOfBytesRead);
    } while (networkStream.DataAvailable);
}

private int GetBufferSize()
{
    byte[] myReadBuffer = new byte[4];
    int numberOfBytesRead = 0;

    do
    {
        numberOfBytesRead = networkStream.Read(myReadBuffer, 0, myReadBuffer.Length);
    } while (networkStream.DataAvailable);

    if (numberOfBytesRead > 0)
    {
        return BitConverter.ToInt32(myReadBuffer, 0);
    }
    else
    {
        return 0;
    }
}

Any ideas?

Upvotes: 0

Views: 132

Answers (2)

Seafko
Seafko

Reputation: 79

Solution

         `return   Int32.Parse(Encoding.UTF8.GetString(myReadBuffer, 0, myReadBuffer.Length))`;

Problem

public void print (int inum)

Prints the string representation of the specified integer to the target.

The Integer get converted to the string representation of that int then converted to bytes.

Upvotes: 1

Tyler Buchanan
Tyler Buchanan

Reputation: 86

It's likely you're having an issue regarding endianness. Java stores data in big endian, and .NET stores data based on your system architecture. If you're on a x86 machine, it's likely you're trying to read big-endian data as if it were little-endian. You'll have to reverse the byte array before reading it

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(buffer);
            }

Here's more info in endianness.

Upvotes: 0

Related Questions