I have an array of int which I want to send to other server using socket programming but it does not work correct I am wondering to know that should I serilized my array or not?
public Integer[] array=new Integer[5];
//I give some dummy value to array then I send. I have no error and the other side
// receive it but with wrong value
in=new ObjectInputStream(client.getInputStream());
out=new ObjectOutputStream(client.getOutputStream());
out.writeObject(new packet(array));
import java.io.Serializable;
public class packet implements Serializable
{
public Integer[] vec=null;
public packet(Integer[] vector){
vec=vector;}
}
//On the other side I have in=new ObjectInputStream(client.getInputStream());
private packet getPacket() throws IOException
{
packet p;
try {
p=(packet) in.readObject();
if (p != null)
return p;
}
}
`
Everything here is OK. The devil is in the details, though. It’s clear that this isn’t the real code, but rather your summary of the code, and so you’ve accidentally fixed something while summarizing it. The most likely problem you’re having is that Java serialization will, by default, only write a given object to a stream once; so if you write an array, change the contents, and write it again, the second instance will come over the wire as just a reference to the first, with the first set of values. Cloning the array in your “packet” constructor, as someone else has mentioned, would definitely help!