【问题标题】:Sending object, int and String via socket, serialisation通过套接字发送对象、int 和 String、序列化
【发布时间】:2013-11-30 16:26:19
【问题描述】:

所以当用户单击列表时,我有一个 PrintWriter 和一个 ObjectOutputStream 试图从客户端发送一个 int、String 和一个 Color[],其中“out”是 PrintWriter,outObject 是 ObjectOutputStream。

private class MyMouseListener implements MouseListener{
  public void mouseExited(MouseEvent e){}
  public void mouseEntered(MouseEvent e){}
  public void mouseClicked(MouseEvent e){
      if(e.getSource() == list){
          int index = list.locationToIndex(e.getPoint());   ///get the game that the player has selected          
          try{
              out.println(index);
                              out.println("hel");
                              Color[] colors = new Color[5];
                              outObject.writeObject(colors)
          }
}

服务器,其中 'in' 是扫描仪,'objectIn' 是 objectInputStream :

                while(true)
                    if(in.nextLine().equals("hel")){
                    System.out.println("fee");
                }
                else if(in.hasNextInt()){
                    System.out.println("dee");
                }
                Object o = objectIn.readObject();
                if(o instanceof Color[]){
                    System.out.println("ree");
                }

如果我尝试发送所有三个,第一次点击服务器只注册字符串,然后服务器只注册 int 之后的所有点击,从不注册 Color[],如果我先发送 int,那么Color[] 然后是 int :`

                              out.println(index);
                              Color[] colors = new Color[5];
                              outObject.writeObject(colors);
                              out.println("hel");

首先仅注册 int 和 Object,第二次仅单击 String,随后仅单击 int。 `

                Object o = objectIn.readObject();
                if(in.nextLine().equals("hel")){
                    System.out.println("fee");
                }
                //Object o = objectIn.readObject(); 
                else if(in.hasNextInt()){
                    System.out.println("dee");
                }
                else if(o instanceof Color[]){
                    System.out.println("ree");
                    o = null;
                }

如果我使用上述一系列 if 语句,则不会注册任何内容

使用第一系列的 if 语句,如果我尝试单独发送 Color[],则它没有注册,但如果我使用 int 发送它,两者都已注册。 如果我尝试发送字符串和颜色 [],请先发送字符串,如下所示:

              out.println("hel");
              Color[] a = new Color[5];
              outObject.writeObject(a);

两者都注册一次,然后再也不注册,也以与预期相反的方式注册,即先注册 Color[],然后注册 String;如果我先发送除了 Color[] 之外的两个字符串,然后字符串都没有注册。

【问题讨论】:

    标签: java serialization


    【解决方案1】:

    我假设您的out 对象(即PrintWriter)包装了outObject 对象,即ObjectOutputStream。您不应将PrintWriterObjectOutputStream 用于同一底层连接。详情请见this question

    【讨论】:

    • 我认为扫描仪会像我们那样干扰对象输入?,并不是说我想要一个没有打印机的扫描仪
    猜你喜欢
    • 2011-06-21
    • 2011-05-14
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 2013-09-11
    • 2012-03-13
    • 2017-03-20
    相关资源
    最近更新 更多