首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java序列化问题

Java序列化问题
EN

Stack Overflow用户
提问于 2010-04-22 21:19:32
回答 4查看 279关注 0票数 2

我有X级和Y级,如下所示:

代码语言:javascript
复制
class X implements Serializable
{
  int val1;
  Y val2;
}

class Y implements Serializable
{
  int val;
}

我想把X类型的对象从一个客户端传送到服务器,但是我不能,因为类X有一个Y类型的字段。我在类X中用X类型的字段替换了Y类型的字段,它可以工作。

编辑--这些是我的类:

代码语言:javascript
复制
class Y implements Serializable
{
  int val;
  Y()
  {
    val = 3;
  }
}

class X implements Serializable
{
  int val;
  Y ob;

  X(int i, Y o)
  {
    val = i;
    ob = o;
  }
}

public class Server
{
  public static void main(String[] s)
  {
    ServerSocket ss = null;
    Socket cs = null;
    ObjectInputStream ois = null;
    ObjectOutputStream oos = null;

    try
    {
    ss = new ServerSocket(1234);
    System.out.println("Server pornit!");
    cs = ss.accept();

    oos = new ObjectOutputStream(cs.getOutputStream());
    ois = new ObjectInputStream(cs.getInputStream());
    }
    catch(Exception e)
    {
      System.out.println("Exceptie!");
    }

    System.out.println("Asteapta mesaj...");
    X x;

    try
    {
    x = (X) ois.readObject();
    System.out.println(x.val);

    }
    catch(Exception e)
    {
      System.out.println(e.toString());
    }
    try
    {
    ss.close();
    cs.close();
    }
    catch(Exception e)
    {
    }

  }
}
public class Client
{
  public static void main(String[] s)
  {
    Socket cs;
    ObjectInputStream ois = null;
    ObjectOutputStream oos = null;

    System.out.println("Connect...");
    try
    {
    cs = new Socket("127.0.0.1",1234);

    oos = new ObjectOutputStream(cs.getOutputStream());
    ois = new ObjectInputStream(cs.getInputStream());
    }
    catch(Exception e)
    {
      System.out.println("Exceptie!");
    }


    try
    {
    oos.writeObject(new X(8,new Y()));
    }
    catch(Exception e)
    {
      System.out.println(e.getMessage());
    }
  }
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-04-22 22:14:39

好的,我想我找到问题了。客户端进程在关闭输出流之前过早终止。因此,服务器将得到意外的断开连接。将oos.close()添加到客户端代码中。

票数 1
EN

Stack Overflow用户

发布于 2010-04-22 21:35:07

检查远程客户端是否可以访问X和(特别是) Y的.class文件?

特别是,如果new Y()没有成功,您就会遇到以下问题:-)

(你的错误是什么?)

票数 0
EN

Stack Overflow用户

发布于 2010-04-22 21:51:19

注意:移到原来的帖子

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2694589

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档