0

I am trying to read a byte[] in my Java application sent from a C# application.

However, when I encode the string to byte[] in C# and reads it in Java, using the code below, I get all the characters but the last. Why is that?

Java receiving code:

int data = streamFromClient.read();
while(data != -1){
    char theChar = (char) data;
    data = streamFromClient.read();
    System.out.println("" + theChar);
}

C# sending code:

public void WriteMessage(string msg){

    byte[] msgBuffer = Encoding.Default.GetBytes(msg);
    sck.Send(msgBuffer, 0, msgBuffer.Length, 0);
}
3
  • 2
    My guess is you are not sending the last character. Commented Feb 13, 2014 at 14:46
  • ^yes lol. Can we see your sending code? Commented Feb 13, 2014 at 14:47
  • I added the C# code to the post Commented Feb 13, 2014 at 15:08

3 Answers 3

2

While others already have provided a possible solution, i want to show how i would solve this.

int data;
while((data=streamFromClient.read()) != -1) {
  char theChar = (char) data;
  System.out.println("" + theChar);
}

I just feel like this approach would be a little more clear. Feel free to choose which you like better.

To clarify: There is an error in your receiving code. You read the last byte but you never process it. On every iteration you print out the value of the byte received in the previous iteration. So the last byte would be processed when data is -1 but you don't enter the loop so it isn't printed.

Sign up to request clarification or add additional context in comments.

1 Comment

There is no need to initialize "data" to -1.
1

You need to read the data untill unless it is becomes -1. so you need to move the reading statement inside infinite loop i.e. while(true) and comeout from it once if the result is -1.

Try This:

 int data = -1;
 while(true){
 data=streamFromClient.read();
 if(data==-1)
 {     
    break;
 }
 char theChar = (char) data;     
 System.out.println("" + theChar);
 }

2 Comments

You call read() twice in the while loop, which is invalid I think. You'll miss half the characters.
@C4stor: that is mistake, i forgot to remove that after copying actual code from OP's post, thank you
-2

I thought that your while loop might have been off by 1 iteration somehow but it seems to me that your C# program is simply not sending all the characters.

1 Comment

I'm not sure why I have received a down vote or why the accepted solution is "accepted". Yes, it prints the value from the previous iteration each time through the loop but when data is -1 in the previous iteration that means there is no more to process. Therefore there is no reason to go through the loop again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.