Dhruv Marwha
Dhruv Marwha

Reputation: 1074

Cannot VIew the Data Sent By a TCP Packet Sending Program(Packet Server)

I'm trying to develop a small app which receives some data via sockets and based on the data it receives,it prints a toast message for the user.I' getting the data,but the data apparently cannot be read properly.Here is the relavent portion for the same.

 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);
         }

This code runs on a separate thread as android does not allow networking operations on a separate thread.

Logcat

The 4 Diamonds is the data displayed by the android studio and cs is the name of the socket which accepts connections.

Thanks.

Upvotes: 0

Views: 72

Answers (1)

President James K. Polk
President James K. Polk

Reputation: 42018

You are simply printing the String that encodes to zero bytes since you never copy the data that is read in.

It would make more sense to convert the byte array to a hex string if the array contains arbitrary data: see the answers to this question for options for that.

If the array contains the encoding of a String in some charset, for example UTF-8, then do the following:

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

Upvotes: 1

Related Questions