【发布时间】:2020-05-24 09:43:23
【问题描述】:
作为一个学校项目,我必须在 Android 和 Java 上创建一个共享对象的应用程序,为此它需要使用对象输入和输出流(如果它不是有效的通信也没关系)。
问题:
- 在初始化 ObjectInputStream 时,服务器端停止并坐在那里
- 当我手动强制关闭应用程序(客户端)时,它会引发异常
服务器端
public class Connection extends Thread {
public final String address;
public final int port;
public final ArrayList<Device> devices;
public Connection(String address, int port) {
this.address = address;
this.port = port;
this.devices = new ArrayList<>();
}
// listen for connections
@Override
public void run() {
try {
ServerSocket server = new ServerSocket(this.port);
while(true){
Socket socket = server.accept();
// it stops here idk why
ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
String name = (String) ;
devices.add(new Device(name,socket,input));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端
public class Connection extends Thread {
private Socket connection;
private ObjectInputStream input;
private ObjectOutputStream output;
private final String name;
private final String address;
private final int port;
public Connection(String name, String address, int port) {
this.name = name;
this.address = address;
this.port = port;
}
@Override
public void run() {
try {
System.out.println("Initializing connection");
// initializes the socket and the streams
initConnection();
System.out.println("Connection established");
// sends the id of the device
sendIdentification(); // sends this.name but the code stops before sending the id idk why
/*The code continues here but you shouldn't care cause the problem comes before*/
} catch (Exception e) {
// on connection failed tries reconnecting
System.out.println("Trying connecting to Server please wait...");
new Thread(new Connection(name,address,port)).start(); // you should not care even about this cause the connection the first time always goes ok
}
}
// init the connection
private void initConnection() throws Exception {
this.connection = new Socket(address, port);
this.input = new ObjectInputStream(this.connection.getInputStream());
this.output = new ObjectOutputStream(this.connection.getOutputStream());
}
}
例外
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2681)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:3156)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:862)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:358)
at bane.connection.Connection.run(Connection.java:31)
【问题讨论】:
标签: java android sockets object serialization