简体   繁体   English

使用Java发送对象时如何停止从BufferedReader读取?

[英]How to Stop Reading From a BufferedReader when sending an Object in Java?

I´m writing a java program that sends an object converted to a byte array through a socket. 我正在编写一个Java程序,该程序通过套接字发送转换为字节数组的对象。 The client has to read all the bytes and translate it back to a Java Object. 客户端必须读取所有字节并将其转换回Java对象。 However I´m having my program stuck on a read() inside the loop where I read all bytes until I find a -1. 但是,我的程序停留在循环内的read()在该循环中我读取所有字节,直到找到-1。

I've read the docs and it says that the read() method return a -1 when reaching the end of the stream, but this is not working. 我已经阅读了文档,并说read()方法在到达流的末尾时返回-1,但这不起作用。

Heres my code: Method for sending an object: 这是我的代码:发送对象的方法:

Socket socket;
BufferedReader input;
DataOutputStream output;
boolean connectionOpen;  //Just for you to know the types of the attributes of my class
 public void sendResponse(Object obj) throws IOException{

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = null;
    try {
      out = new ObjectOutputStream(bos);   
      out.writeObject(obj);
      byte[] yourBytes = bos.toByteArray();


      output.write(yourBytes);

    } finally {
      try {
        if (out != null) {
          out.close();
        }
      } catch (IOException ex) {
        // ignore close exception
      }
      try {
        bos.close();
      } catch (IOException ex) {
        // ignore close exception
      }
    }  


}     

Method For reading the bytes. 方法用于读取字节。 (This is where my code gets stuck) (这是我的代码卡住的地方)

public Email getMail(int id) throws Exception{
    byte[] bytes = new byte[50000];
    Email result;
    try{
        this.outToServer.writeBytes("MAIL "+id+"\n");
        String response = inFromServer.readLine();
        String[] data = response.split(" ");
        int code = Integer.parseInt(data[0]); 
        if(code==500){
            throw new Exception("Error en servidor Pop4. Servidor respondio: "+response);
        }
        int current =  inFromServer.read();
                int i = 0;

        while(current!=-1){

            bytes[i]=(byte) current;
            i++;
            current= inFromServer.read();
        }
        //Convertimos el arreglo de bytes a un objeto Email
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInput in = null;
        try {
          in = new ObjectInputStream(bis);
          result = (Email) in.readObject(); 

        } finally {
          try {
            bis.close();
          } catch (IOException ex) {
            // ignore close exception
          }
          try {
            if (in != null) {
              in.close();
            }
          } catch (IOException ex) {
            // ignore close exception
              ex.printStackTrace();
          }
        }            
    }

    catch(Exception e){
            throw e;
    }
    return result;


}

I suggest you read one object at a time directly from the socket. 我建议您一次直接从套接字读取一个对象。

final ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());

public void sendMessage(Object obj) {
    out.writeObject(obj);
    out.reset();
    out.flush();
}

final ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

public Object readMessage() {
    return in.readObject();
}

In short, you need to know when you should stop reading or use a stream which does. 简而言之,您需要知道什么时候应该停止阅读或使用流媒体。

The docs are quite right that InputStream.read() returns -1 when it cannot transfer any bytes because it has reached the end of the stream. 文档非常正确,当InputStream.read()已到达流的末尾而无法传输任何字节时,它返回-1。 However, nothing in what you presented gives me any reason to think that condition will be satisfied. 但是,您提出的内容并没有使我有任何理由认为条件会得到满足。

End of stream corresponds to a condition in which it is certain that no more bytes ever will be received from the stream. 流的末尾对应于确定从该流不再接收到任何字节的条件。 That is not at all the same thing as there being no more bytes available at any given time. 完全不同,因为在任何给定时间都没有可用的字节。 If the sender indeed has nothing further to say for the remaining life of the connection, then it should close the OutputStream for its end of the connection. 如果发送方对于连接的剩余生命确实没有话要说,那么它应该在连接结束时关闭 OutputStream After it does so, the reader should detect end-of-stream. 在这样做之后,阅读器应该检测到流的末尾。 You presented no evidence that you do that. 您没有提供证明您这样做的证据。

If the sender is not ready to close the stream, then you need to devise a different way for the receiver to know when to stop reading. 如果发送者还没有准备好关闭流,那么您需要设计一种不同的方式让接收者知道何时停止阅读。 That implies some kind of application-layer protocol on top of the stream. 这意味着在流之上需要某种应用层协议。 One of the simplest of such protocols involves sending messages consisting of a fixed-width byte-count followed by the specified number of bytes. 这种协议中最简单的一种涉及发送由固定宽度字节数后跟指定字节数的消息组成的消息。

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

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