【问题标题】:Cannot VIew the Data Sent By a TCP Packet Sending Program(Packet Server)无法查看 TCP 数据包发送程序(数据包服务器)发送的数据
【发布时间】:2017-12-28 07:53:34
【问题描述】:

我正在尝试开发一个小型应用程序,它通过套接字接收一些数据并根据它接收到的数据为用户打印一条 toast 消息。我正在获取数据,但显然无法正确读取数据。这是相同的相关部分。

 int red = -1;
 byte[] buffer = new byte[1024]; // a read buffer of 5KiB
 byte[] redData;


 while ((red = cs.getInputStream().read(buffer)) > -1) {
     String redDataTextappend;

     redData = new byte[red];

     redDataTextappend = new String(redData);
     Log.w("Data got",redDataTextappend);

     if (redDataTextappend == "hi") 
       {
         //Display Toast message using runonUIThread(new Runnable);
       }
     else 
         {//Display Message Using runonUITHread(new Runnable);
         }

此代码在单独的线程上运行,因为 android 不允许在单独的线程上进行网络操作。

4 Diamonds是android studio显示的数据,cs是接受连接的socket的名称。

谢谢。

【问题讨论】:

    标签: android multithreading sockets tcp


    【解决方案1】:

    您只是打印编码为零字节的字符串,因为您从不复制读入的数据。

    如果数组包含任意数据,将字节数组转换为十六进制字符串会更有意义:有关选项,请参阅this question 的答案。

    如果数组包含某个字符集中的字符串编码,例如 UTF-8,则执行以下操作:

    byte[] redData = Arrays.copyOf(buffer, red);
    String redDataTextappend = new String(redData, Charset.forName("UTF-8"));
    Log.w("Data got",redDataTextappend);
    

    【讨论】:

    • 我已经通过直接读取字节值来解决这个问题。对于以字节或字符串形式发送数据,我应该使用什么方法?
    • @DhruvMarwha:这取决于应用程序的细节。
    • 我试过readUTF之类的方法,但都不管用。您能给点意见吗?
    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 2015-04-10
    相关资源
    最近更新 更多