简体   繁体   English

Java套接字从C#读取字节

[英]Java socket read bytes from C#

I am trying to read a byte[] in my Java application sent from a C# application. 我正在尝试从C#应用程序发送的Java应用程序中读取byte[]

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. 但是,当我使用下面的代码在C#中将string编码为byte[]并在Java中读取它时,我得到了除最后一个字符以外的所有字符。 Why is that? 这是为什么?

Java receiving code: Java接收代码:

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

C# sending code: C#发送代码:

public void WriteMessage(string msg){

    byte[] msgBuffer = Encoding.Default.GetBytes(msg);
    sck.Send(msgBuffer, 0, msgBuffer.Length, 0);
}

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. 因此,当数据为-1时将处理最后一个字节,但您无需进入循环,因此不会打印该循环。

You need to read the data untill unless it is becomes -1 . 您需要读取数据,直到它变为-1为止。 so you need to move the reading statement inside infinite loop ie while(true) and comeout from it once if the result is -1 . 因此,您需要在infinite loopwhile(true)内移动读取语句,如果结果为-1则从语句中取出一次。

Try This: 尝试这个:

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

我以为您的while循环可能以某种方式被1次迭代关闭了,但是在我看来,您的C#程序根本就没有发送所有字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM