通过套接字串行化发送对象、int和String



因此,当用户单击列表时,我有一个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");
                }

如果我尝试发送这三个,第一次点击时服务器只注册String,然后所有点击后服务器只注册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[]和String。

我假设您的out对象(它是一个PrintWriter)包装了outObject对象,它是ObjectOutputStream。对于同一个底层连接,不应同时使用PrintWriterObjectOutputStream。有关详细信息,请参阅此问题。

最新更新