通过套接字发送一个可序列化的对象 [英] send a serializable object over socket

查看:83
本文介绍了通过套接字发送一个可序列化的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在发送通过套接字创建的可序列化对象时遇到了一个奇怪的问题.事实上,如果我在同一台机器上运行服务器和客户端,它运行良好,但如果服务器和客户端在不同的机器上,则服务器端的 readen 对象为空(大小为零)

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)

服务器:

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

客户:

public static void main () {
...
ObjectOutputStream oos = new ObjectOutputStream(mysocket.getOutputStream());
oos.writeObject(list_of_object);
...
}

推荐答案

使用您的 MyObject 类版本尝试以下测试用例.它将帮助您找出问题所在.如果这对您的班级工作正常,那么它可能是网络层,例如您正在阅读与您期望阅读的内容不同的内容.常见的错误可能是您在某处运行旧版本的服务器代码,并且您可能确实读取了 MyObjects 的空列表.

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

}

这篇关于通过套接字发送一个可序列化的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆