Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

java - send a serializable object over socket

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

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

1 Reply

0 votes
by (71.8m points)

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());
}

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...