Java serialization problem

I have two classes X and Y, for example:

class X implements Serializable
{
  int val1;
  Y val2;
}

class Y implements Serializable
{
  int val;
}

      

I want to pass an object of type X from client to server, but I can't because class X has field of type Y. I replaced field of type Y with field of type X in class X and it works.

EDIT These are my classes:

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

      

+2


a source to share


4 answers


Ok, I guess I found the problem. The client process ends prematurely before closing the output stream. As a result, the server receives an unexpected shutdown. Add oos.close () code to client code.



+1


a source


Make sure the remote client can access the .class files for X and (in particular) Y?

Specifically, if the new Y () fails, you have a problem :-)



(What error are you getting?)

0


a source


Note from oreyes: Moved to original post

0


a source


It works on my machine:

$javac X.java  
$java Server & 
[1] 14037
$Server pornit!
java Client 
Connect...
Asteapta mesaj...
$8

      

I wonder if you are not killing the server when starting the client.

0


a source







All Articles