简体   繁体   English

C#服务器和Java客户端TCP

[英]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. 问题是GetBufferSize方法,我发送的缓冲区大小为40,它返回一些奇怪的数字54124。
Why is this dose the java int byte code different from C# int byte code? 为什么java int字节码与C#int字节码不同?

JAVA CLIENT JAVA客户端

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 C#服务器

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? 有任何想法吗?

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. 将Integer转换为该int的字符串表示形式,然后转换为字节。

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. Java将数据存储在big endian中,.NET根据您的系统体系结构存储数据。 If you're on a x86 machine, it's likely you're trying to read big-endian data as if it were little-endian. 如果您使用的是x86机器,则可能正试图读取大端数据,就好像它是小端数据一样。 You'll have to reverse the byte array before reading it 您必须在读取字节数组之前将其反转

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

Here's more info in endianness. 这是有关字节顺序的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM