Dans le cadre d'un projet scolaire, je dois créer une application sur Android et Java qui partage des objets. Pour cela, il faut utiliser des flux d'entrée et de sortie d'objets (peu importe si la communication n'est pas efficace).
Problèmes :
- Le côté serveur s'arrête et reste là lorsque l'ObjectInputStream est initialisé.
- Lorsque je force manuellement la fermeture de l'application (côté client), une exception se produit.
Côté serveur
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();
}
}
}
Côté client
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());
}
}
Excepción
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)