I’m making simple peer to peer game and I decided to use XML to send information over sockets(example below). But I’m not sure how to send it ? I should simply use ObjectOutputStream.writeObject(obj) and as parameter use object from my example ?
Mainly I’m asking, how does look proper sending XML objects over sockets.
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class SendIPObject {
public static void main(String[] args) throws Exception {
JAXBContext context = JAXBContext.newInstance(IPSender.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Player object = new Player();
object.setID(0);
object.setIP("192.167.211.167");
m.marshal(object, System.out);
}
}
import java.io.Serializable;
abstract public class Player implements Serializable{
private String ip;
private int id;
public String getIP() {
return ip;
}
public int getID() {
return id;
}
public void setIP(String ip) {
this.ip = ip;
}
public void setID(int id) {
this.id = id;
}
}
XML is sent as plain string. So first step would be to create clients that can send and receive from each other strings, e.g. “Hello, world.”. Next you need to create an object and using JAXB convert to String and send. Than receive it on other client and using JAXB again. This way you can easily debug what you send and receive. Once you’ve done it you can try to avoid converting to temporary xml string and use socket streams directly on marshalling and unmarshalling.
I think you shouldn’t use
ObjectOutputStreambecause it serializes object to byte array. But you need to “serialize” your object to XML (string) and send it.Here you can see how can you marshal object to java
String: I want to convert an output stream into String object