我有兩個類X和Y,像這樣:Java序列化問題
class X implements Serializable
{
int val1;
Y val2;
}
class Y implements Serializable
{
int val;
}
我想從客戶端到服務器傳輸X類型的對象,但我不能,因爲類X有一個字段Y類型。我用X類型的字段替換了Y類型的字段,它起作用。
編輯 這些都是我的課:
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());
}
}
}
你使用ObjectOutputStream和ObjectInputStream嗎?你看到什麼樣的錯誤?如果你使用2個進程:你確定你爲它們提供了相同版本的編譯類嗎? – 2010-04-22 21:25:08
一些序列化代碼如何?堆棧痕跡?你不能傳送一個'X'實例?爲什麼不?當你嘗試時會發生什麼?當你把'Y'改成'X'和「它有效」時,這到底意味着什麼? – erickson 2010-04-22 21:28:15
是的,我使用ObjectOutputStream和ObjectInputStream,並且是相同的類在客戶端和服務器。服務器在接收到X類型對象時拋出異常。 例外情況是:「java.net.SocketException:連接重置」 – Stefan 2010-04-22 21:41:07