繁体   English   中英

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

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

我正在编写一个Java程序,该程序通过套接字发送转换为字节数组的对象。 客户端必须读取所有字节并将其转换回Java对象。 但是,我的程序停留在循环内的read()在该循环中我读取所有字节,直到找到-1。

我已经阅读了文档,并说read()方法在到达流的末尾时返回-1,但这不起作用。

这是我的代码:发送对象的方法:

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


}     

方法用于读取字节。 (这是我的代码卡住的地方)

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;


}

我建议您一次直接从套接字读取一个对象。

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

简而言之,您需要知道什么时候应该停止阅读或使用流媒体。

文档非常正确,当InputStream.read()已到达流的末尾而无法传输任何字节时,它返回-1。 但是,您提出的内容并没有使我有任何理由认为条件会得到满足。

流的末尾对应于确定从该流不再接收到任何字节的条件。 完全不同,因为在任何给定时间都没有可用的字节。 如果发送方对于连接的剩余生命确实没有话要说,那么它应该在连接结束时关闭 OutputStream 在这样做之后,阅读器应该检测到流的末尾。 您没有提供证明您这样做的证据。

如果发送者还没有准备好关闭流,那么您需要设计一种不同的方式让接收者知道何时停止阅读。 这意味着在流之上需要某种应用层协议。 这种协议中最简单的一种涉及发送由固定宽度字节数后跟指定字节数的消息组成的消息。

暂无
暂无

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

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