简体   繁体   中英

Error reading from a socket in java

On the one side of the socket I know the data is going into the socket correctly.

I set up a connection:

Connection sr = new Connection();
Server server = new Server("NAME", Interger.parseInt(port));
server.setIp(ip);
sr.setServer(server); 

//I know my server connection code is correct because I can send and receive data in 
//other areas of my program just fine

InputStream is = null;

try
{
  is = sr.getChannel().socket().getInputStream();

  BufferedReader br = new BufferedReader(new InputStreamReader(is));
  StringBuffer text = new StringBuffer();

  int k =0;

  while(k != -1)
  {
    k = br.read();
    text.append((char) k);
  }
}
catch(Exception e)
{
  //no errors ever get thrown
}

And then I only get about half my data, 10989 bytes out of a total 21398 that I send. The amount of bytes it reads varies but the data always ends with ..., "values": [" which in the data I send over looks like , ..., "values": ["", ""] .

Keep reading until you have all the data. This question has been showing up about once a week lately. There's no guarantee that the network is going to have all your data show up at once.

You need to keep reading until you have all your data. How do you know how much data was sent? You should probably build a little protocol between the client/server that defines how much data is going to be sent, the server reads that little header and continues to read until the full message has been received.

Don't know if this could help you :

int k =0;

while((k = br.read()) != -1){
   text.append((char) k);
}

1) In your case it is making the check on the next iteration , which may lead to appending of non-representable character( char of -1) to the end of text .

2) Never leave catch block empty, may be there is some execption .

So because my sending side of the socket was in c++ I was accidentally passing in a null ASCII value into the socket. And it is undocumented on the java side of the socket that if the read encounters a null value it treats it as an end of file. So it was prematurely ending the stream because it hit the null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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