I need to upload a file over a udp connection to a college job. I created a package class that contains the header and part of the file to be submitted. I made 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 tried the methods without sending over the connection and they worked, but when I send it through the datagram and the conversion is done back to Object it gives the error: java.io.StreamCorruptedException: invalid type code: 00 Just in this line:
Object object = objectInputStream.readObject();
Does anyone know what it can be?
Client Class method that starts sending packets:
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 packet is sent and then the error occurs when it arrives at the server on the thread that receives the packets:
public void run() {
for (DatagramPacket pkg : servidor.getPacotes()) {
try {
Pacote pct = (Pacote) Manipulador.converterParaObject(pkg.getData());
int flag = pct.getFlag();
At the time of converting the bytes received into the Package object. I had put a println upon receipt of the response from the server that never runs, so I realized that the error happens on the first submission.