簡體   English   中英

通過 Android socket 發送和接收 Bytes 兩個問題:

[英]Sending and receiving Bytes over Android socket two issues:

我遇到了 JAVA/Android 工作室圍繞發送和接收字節的問題。 值得注意的是:使用 TCP sockets 發送和接收超過 127 的字節值。

我在這里收到數據:

    try {
        mBufferOut = new PrintWriter(socket.getOutputStream());
        mBufferIn = new InputStreamReader(socket.getInputStream(), "UTF-8");
        char[] buffer = new char[64];

        while (mRun) {
mBufferIn.read(buffer);
            mServerMessage = String.valueOf(buffer);
            if (mServerMessage != null && mMessageListener != null) {
                mMessageListener.messageReceived(mServerMessage);
            }
            mServerMessage = null;
        }

並在此處發送數據:

public void sendMessage(final char[] message) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (mBufferOut != null) {
                    mBufferOut.write(message);
                    mBufferOut.flush();
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }

當我收到數據時,所有超過 127 的數據都返回為“231、191、189”。 當我發送數據時,值 x 超過 127 的每個字節都返回為“195,x”。

我怎樣才能干凈地解決這個問題?

我不認為將String作為char數組發送,並使用String.valueOf()來恢復它是正確的方法。

String已經有一種將自身轉換為字節的機制:

byte[] bytes = text.getBytes("UTF-8");
...
String text = new String(bytes, "UTF-8");

嘗試使用這 2 種方法將String轉換為byte[] ,反之亦然。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM