2

我试图从我的安卓手机发送一个对象到我的电脑,但我一直收到这个错误,它无法识别这个对象的类。这很奇怪,因为当我尝试将对象从计算机发送到自身时,它使用相同的方式工作。这两个包都有 User 类,并且它实现了 Serializable。请告诉我为什么会这样。

计算机(服务器):

private ServerSocket server;
private ObjectInputStream input;
private Socket connection;
private User message;

public void brains() throws IOException {
    while (true) {
        System.out.println("waiting for connection...");
        try {
            server = new ServerSocket(4567, 100);
            connection = server.accept();
            System.out.println("you are now conected");
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        System.out.println("Setting up Streams..");

        input = new ObjectInputStream(connection.getInputStream());
        try {
            message = (User) input.readObject();
        } catch (ClassNotFoundException ex) {
            System.out.println("I dont know wtf");
        }

        System.out.print("the user ");
        message.printUserName();
        System.out.print(", used your app at ");
        message.printTime();
        System.out.println("");
                    System.out.println("Shutting down!");
        try {
            input.close();
            connection.close();
            server.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }

    }

}

电话(客户):

private User user;
private Socket connection;
private ObjectOutputStream output;

public void run() {

    try{
    connection = new Socket (InetAddress.getByName(ip), 4567);
    output = new ObjectOutputStream(connection.getOutputStream()) ;

    user = new User("bla bla", "14:09");
    output.writeObject(user);
    output.flush();



    }catch(Exception e){
        System.out.print(e);
    }finally{
        try{
        output.close();
        connection.close();
        }
    catch(Exception e){
        System.out.print(e);
    }




    }



}

这是控制台日志:

waiting for connection...
you are now conected
Setting up Streams..
Dont recognize the class
the user Exception in thread "main" java.lang.NullPointerException
at whosUsing.whosUsing.brains(whosUsing.java:34)
at whosUsing.test.main(test.java:9)
4

2 回答 2

0

如果一个类在客户端和服务器端的包中并不完全相同,那么通过的类将不会被系统识别。

将 User.java 文件放在同一个包中:“com.myapp.shared.User”。这应该可以解决您的问题。

有关类似问题,请参阅readobject 方法 throws ClassNotFoundException 。

于 2013-11-11T00:04:08.737 回答
0

确保手机端客户端的包名和类名必须与电脑端的服务器端完全相同。看看这个。希望有帮助

ObjectInputStream readObject(): ClassNotFoundException

于 2013-11-11T00:16:37.057 回答