Patrick Reck
Patrick Reck

Reputation: 11374

Java socket read bytes from C#

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

Upvotes: 0

Views: 180

Answers (3)

user432
user432

Reputation: 3534

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.

Upvotes: 2

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

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

Upvotes: 1

M7Jacks
M7Jacks

Reputation: 124

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.

Upvotes: -2

Related Questions