我正在寫一個java程序,通過套接字發送一個對象轉換爲字節數組。客戶端必須讀取所有字節並將其翻譯回Java對象。然而,我的程序卡在循環內的read()
,我讀取所有字節,直到找到-1。如何在Java中發送對象時停止從BufferedReader讀取數據?
我讀過文檔,它說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;
}
非常感謝。那麼我將實現一個應用層協議。 –