views:

89

answers:

4

I have two classes X and Y, like this:

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

class Y implements Serializable
{
  int val;
}

I want to transmit an object of type X from a client to server but i can't because the class X has a field of type Y. I replaced the field of type Y with a 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());
    }
  }
}
A: 

Check that the remote client has access to the .class files for both X and (in particular) Y?

In particular, if new Y() does not succeed you have a problem :-)

(What is the error you're getting?)

Steven Schlansker
A: 

Note by oreyes: moved to the original post

Stefan
A: 

It works on my machine:

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

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

OscarRyz
+1  A: 

Ok I think I found the problem. The client process terminates prematurely, before closing the output stream. As a result, the server gets an unexpected disconnection. Add oos.close() to the client code.

Eyal Schneider
Eyal is right. Now it works...Thanks all !!!
Stefan