我正在开发Android Studio中的项目。 计划是通过Java(Eclipse)中的本地服务器将对象发送到在Android Studio中编程的移动应用程序。以下是服务器的代码:
public Server() {
ServerSocket server = null;
try {
server = new ServerSocket(1010);
} catch (IOException e) {
e.printStackTrace();
}
ObjectOutputStream oos;
try {
while (true) {
Socket s = server.accept();
System.out.println("new client");
oos = new ObjectOutputStream(s.getOutputStream());
oos.writeObject(new Packet("Hi"));
System.out.println("Objekt versendet");
oos.flush();
oos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
来自客户:
public Client() {
Socket s = null;
try {
s = new Socket("localhost", 1010);
} catch (IOException e) {
e.printStackTrace();
}
try {
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
Object o;
o = ois.readObject();
Packet p = (Packet) o;
System.out.println("[Von Server]: " + p.getS());
s.close();
} catch ( IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
当新客户端连接到服务器时,它应该向客户端发送一个数据包,包括名为" hi"的字符串。 当我在Eclipse中启动服务器和客户端时,它工作正常。 当我在Android Studio(VD)中启动客户端时,虽然Class Packet已存在,但此错误仍会出现:
ava.lang.ClassNotFoundException: Packet
W/System.err: at java.lang.Class.classForName(Native Method)
W/System.err: at java.lang.Class.forName(Class.java:324)
W/System.err: at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:2258)
W/System.err: at java.io.ObjectInputStream.readNewClassDesc(ObjectInputStream.java:1641)
W/System.err: at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:657)
W/System.err: at java.io.ObjectInputStream.readNewObject(ObjectInputStream.java:1782)
W/System.err: at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:761)
W/System.err: at java.io.ObjectInputStream.readObject(ObjectInputStream.java:1983)
W/System.err: at java.io.ObjectInputStream.readObject(ObjectInputStream.java:1940)