2017-04-16 96 views
0

這裏是我的服務器類,我想發送簡單的類'heee',但每次連接到客戶端時,我都會從try catch獲取'用戶未發送'。我究竟做錯了什麼?如何通過java中的套接字發送和接收對象

public class heee{ 

    String me = "hehehe"; 
} 
public static void main(String args[]) throws Exception { 
    ServerSocket ssock = new ServerSocket(2222); 
    System.out.println("Listening"); 

    while (true) 
    { 
    Socket sock = ssock.accept(); 
    System.out.println("Connected"); 
    new Thread(new MultiThreadedServer(sock)).start(); 
    } 


} 
@Override 
public void run() { 
    try 
    { 
     out = new ObjectOutputStream(csocket.getOutputStream()); 

     heee hope = new heee(); 
     out.writeObject(hope); 
     System.out.println("debug line"); 

    }catch(Exception ex) 
    { 
     System.out.println("users was not sent"); 
    } 

這裏我想讀取線程中的對象。

public class ChatServer implements Runnable { 

Socket clientSocket = null; 
ObjectInputStream in = null; 

@Override 
public void run() 
{ 
    try 
    { 
     clientSocket = new Socket ("localhost", 2222); 
     in = new ObjectInputStream(clientSocket.getInputStream()); 
     heee nope = (heee) in.readObject(); 
     System.out.print(nope.me); 

    } catch(Exception Ex) 
      { 

      } 

} 



public static void main(String args[]) throws Exception { 

    new Thread(new ChatServer()).start(); 

} 

public class heee{ 

    String me; 
} 

} 
+1

「我做錯了什麼?」您不打印異常。 – tkausl

回答

0

如果您想查看錯誤的真實原因,則需要打印堆棧跟蹤。你趕上NotSerializableException。每個想要寫入或讀取的對象都必須是可序列化的。將implement Serializable添加到heee簽名。

+0

好的我已經在這兩個文件中使heee可序列化並添加了一個catch,並且在客戶端它告訴我寫入在服務器的第43行是run()方法中止,這是異常的第一行' java.io.WriteAbortedException:寫入中止; java.io.NotSerializableException:MultiThreadedServer'和最後一行'由...引發:java.io.NotSerializableException:MultiThreadedServer'在服務器端,它告訴我java.io.NotSerializableException:MultiThreadedServer在java.io.ObjectOutputStream處爲 \t。 writeObject0(ObjectOutputStream.java:1184)',並繼續如此 – Peter

+0

如果你把兩個'heee'類'Serializable'都做了,這個例外就不一定了。 –

+0

現在起作用了,我把課程結構搞砸了 – Peter