2010-04-22 46 views
2

我有兩個類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()); 
    } 
    } 
} 
+0

你使用ObjectOutputStream和ObjectInputStream嗎?你看到什麼樣的錯誤?如果你使用2個進程:你確定你爲它們提供了相同版本的編譯類嗎? – 2010-04-22 21:25:08

+2

一些序列化代碼如何?堆棧痕跡?你不能傳送一個'X'實例?爲什麼不?當你嘗試時會發生什麼?當你把'Y'改成'X'和「它有效」時,這到底意味着什麼? – erickson 2010-04-22 21:28:15

+0

是的,我使用ObjectOutputStream和ObjectInputStream,並且是相同的類在客戶端和服務器。服務器在接收到X類型對象時拋出異常。 例外情況是:「java.net.SocketException:連接重置」 – Stefan 2010-04-22 21:41:07

回答

1

好吧,我想我找到了問題。客戶端進程在關閉輸出流之前過早終止。結果,服務器意外斷開連接。將oos.close()添加到客戶端代碼。

+0

Eyal是對的。現在它的作品... 謝謝大家! – Stefan 2010-04-22 22:42:18

0

檢查遠程客戶端可以訪問的.class文件X和(特別是)Y?

特別是,如果新的Y()不會成功,你必須:-)

(什麼是你得到的錯誤?)

0

說明oreyes一個問題:移動到原來發布

0

它的工作原理在我的機器上:

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

我不知道如果你不殺死服務器在啓動客戶端。