2
I need to send a file over an udp connection to a college paper. I created a package class that contains the header and part of the file to be sent. I did the following method to convert the object to byte[]:
public static byte[] objectToByte(Object obj) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(obj);
objectOutputStream.flush();
objectOutputStream.close();
byteArrayOutputStream.close();
return byteArrayOutputStream.toByteArray();
}
And I created the following to convert back to Object:
public static Object byteToObject(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
Object object = objectInputStream.readObject();
objectInputStream.close();
return object;
}
I tested and the methods without sending by the connection and worked, but when sending by the datagram and will be done the conversion back to Object gives the error: java.io.Streamcorruptedexception: invalid type code: 00 Along those lines:
Object object = objectInputStream.readObject();
Does anyone know what it can be?
Customer Class method that starts sending packages:
public void executa(String host, int porta, String arquivo) throws ClassNotFoundException {
try {
InetAddress addr = InetAddress.getByName(host);
this.porta = porta;
this.caminho = arquivo;
this.host=host;
//Fazendo HandShake
Pacote pct = new Pacote(nSeq,ack,(short)2);
DatagramPacket envio = new DatagramPacket(Manipulador.objectToByte(pct), 12, addr, porta);
client = new DatagramSocket();
//primeira msg
client.send(envio);
The first package is sent and then the error happens when it arrives at the server, in the thread that receives the packages:
public void run() {
for (DatagramPacket pkg : servidor.getPacotes()) {
try {
Pacote pct = (Pacote) Manipulador.converterParaObject(pkg.getData());
int flag = pct.getFlag();
When converting the received bytes to the Package object. I had put a println after receiving the server response that never runs, so I realized that the error happens in the first upload.
By doing a little research, this seems to be a problem with serialization and not necessarily the way you’re doing the conversion. Some class of your project implements the interface
Serializable?– StatelessDev
Yes, the package class, which is the object I send via udp connection.
– Rodrigo Lima
It only implements Serializable and nothing else? If yes, nor need post. Also, post the class that sends via udp.
– StatelessDev
Only implements serializable.
– Rodrigo Lima