-
Notifications
You must be signed in to change notification settings - Fork 1
Description
Context
public Peer handleJoinRequest(HttpExchange exchange, List<Peer> connectedPeersList) {
...
int statusCode = 200;
ByteArrayOutputStream response = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(response);
objectOutputStream.writeObject(peerList);
objectOutputStream.flush();
objectOutputStream.close();
byte[] bytes = response.toByteArray();
exchange.getResponseHeaders().set("Content-Type", "application/octet-stream");
exchange.sendResponseHeaders(statusCode, bytes.length);
exchange.getResponseBody().write(bytes);
exchange.close();
...
}
You can use something like this:
ResponseJoinRequest implements Serializable {
String peerId;
List<Peer> peerList;
}
peerId: the peer ID generated by tracker
peerList: a list of Peers for this peer
With this approach the tracker will generate the peerId and the peer only pass her ip address.
And you could reuse this Response Class in leecher implementation.
Java Serialization Caveats
When a class implements the java.io.Serializable interface, all its sub-classes are serializable as well. Conversely, when an object has a reference to another object, these objects must implement the Serializable interface separately, or else a NotSerializableException will be thrown. take a look:
public class Person implements Serializable {
private int age;
private String name;
private Address country; // must be serializable too
}
If one of the fields in a serializable object consists of an array of objects, then all of these objects must be serializable as well, or else a NotSerializableException will be thrown. source: https://www.baeldung.com/java-serialization