我想通过socket将Object从服务器传递给客户端。客户端在Android上。
我有这个可序列化的类:
public class BoardImage implements Serializable{
private static final long serialVersionUID = 1L;
private String filename;
private int boardNumber;
private int fileSizeInBytes = -1;
private byte imageData[];
public BoardImage(){}
public BoardImage(String filename) {
this.filename = filename;
try{
this.boardNumber = Integer.parseInt(filename.substring(0, filename.indexOf("."))); // takes the filename without extension and converts to int
}
catch (NumberFormatException exp){
this.boardNumber = -1;
}
FileInputStream fin = null;
try {
File file = new File(filename);
fin = new FileInputStream(file);
this.fileSizeInBytes = (int)file.length();
imageData = new byte[fileSizeInBytes];
fin.read(imageData); // read file data into byte array
fin.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(BoardImage.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(BoardImage.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
在服务器端:
BoardImage bImg = new BoardImage(fileToSend);
ObjectOutputStream os = new ObjectOutputStream(connection.getOutputStream());
os.writeObject(bImg);
os.close();
在客户端(Android):
try {
if (read == true){ // try to read from socket stream
rcvdBoard = (BoardImage)ois.readObject(); // <-- HERE WE GET THE EXCEPTION
System.out.println(rcvdBoard.getFileSize()); // print the size of the file
new Thread(){
public void run(){
myParant.addBoard(BitmapFactory.decodeByteArray(rcvdBoard.getFileContent(), 0, rcvdBoard.getFileSize()));
}
}.start();
}
} catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
行:rcvdBoard = (BoardImage)ois.readObject();
java.io.OptionalDataException
logcat的:
04-03 17:47:49.621: W/System.err(3910): java.io.OptionalDataException
04-03 17:47:49.621: W/System.err(3910): at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:810)
04-03 17:47:49.621: W/System.err(3910): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:2006)
04-03 17:47:49.631: W/System.err(3910): at java.io.ObjectInputStream.readObject(ObjectInputStream.java:1963)
04-03 17:47:49.631: W/System.err(3910): at com.example.helloworld.ImageListener.run(ImageListener.java:69)
注意:我尝试在非Android环境中运行客户端,但它确实有效。那么也许它是关于android的东西?
谢谢!
答案 0 :(得分:0)
<强>更新强> 我发现BoardImage.java中的包名应该相同!