Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a strange problem to send a serializable object that I have created over socket. In fact if I run the server and the client in the same machine it works well but if the server and the client are in different machines the readen object in the server side is empty (with size equal to zero)

Any one have an idea to fix that ? (the code is bellow)

Server:

public static void main () {
...
InputStream is = mysocket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);

ArrayList<MyObject> list_of_object;
list_of_object = (ArrayList<MyObject>) ois.readObject();
logger.log(Level.INFO,"object readen with size : "+list_of_object.size());
...
}

Client:

public static void main () {
...
ObjectOutputStream oos = new ObjectOutputStream(mysocket.getOutputStream());
oos.writeObject(list_of_object);
...
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
187 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try the following test case with your version of the MyObject-class. It will help you to figure out the problem. If this works fine with your class, then it may be the network layer, e.g. you're reading something different than what you expect to read. Common mistakes may be that you're running an old version of your server code somewhere and you may indeed read an empty list of MyObjects.

import static org.junit.Assert.assertEquals;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

import org.junit.Test;

public class StreamTest {

public static class MyObject implements Serializable {

}

@Test
public void test() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    ArrayList<MyObject> list_of_object = new ArrayList<MyObject>();
    list_of_object.add(new MyObject());
    oos.writeObject(list_of_object);

    byte[] whatGoesOverWire = baos.toByteArray();
    ByteArrayInputStream bais = new ByteArrayInputStream(whatGoesOverWire);
    ObjectInputStream ois = new ObjectInputStream(bais);
    ArrayList<MyObject> deserialized = (ArrayList<MyObject>) ois
            .readObject();
    assertEquals(1, list_of_object.size());
    assertEquals(1, deserialized.size());
}

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...