1

我想通过套接字将对象从服务器传递到客户端。客户端在 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

日志猫:

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有关?

谢谢!

4

1 回答 1

0

更新: 我发现两个 BoardImage.java 中的包名应该是一样的!

于 2013-04-04T21:50:39.007 回答