send a serializable object over socket

情到浓时终转凉″ 提交于 2019-12-25 18:14:57

问题


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

回答1:


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

}


来源:https://stackoverflow.com/questions/13235377/send-a-serializable-object-over-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!