简体   繁体   English

从Java中的套接字读取时出错

[英]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. 然后我只得到大约一半的数据,即我发送的21398个字节中的10989个字节。 The amount of bytes it reads varies but the data always ends with ..., "values": [" which in the data I send over looks like , ..., "values": ["", ""] . 它读取的字节数各不相同,但是数据始终以..., "values": ["结尾,在我发送的数据中,它看起来像是..., "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 . 1)在您的情况下,它正在检查下一个iteration ,这可能导致在text末尾附加无法代表的字符(-1的char )。

2) Never leave catch block empty, may be there is some execption . 2)切勿将catch block留空,可能会有execption

So because my sending side of the socket was in c++ I was accidentally passing in a null ASCII value into the socket. 因此,因为我的套接字发送端是c ++,所以我不小心将空ASCII值传递给了套接字。 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. 而且套接字的Java端没有记录,如果读取遇到null值,它将把它当作文件的结尾。 So it was prematurely ending the stream because it hit the null. 因此它过早地终止了流,因为它命中了null。

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

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