2015-06-12 102 views
0

您好,我想用Java測試客戶端和服務器之間的連接。例如,我想從客戶端發送一個對象到服務器。該對象是我建立的用戶。如何使用Java將對象從客戶端發送到服務器?

如果我啓動服務器和客戶端我得到這個錯誤:

run: 
java.net.SocketException: Connection reset 
    at java.net.SocketInputStream.read(SocketInputStream.java:209) 
    at java.net.SocketInputStream.read(SocketInputStream.java:141) 
    at java.net.SocketInputStream.read(SocketInputStream.java:223) 
    at java.io.ObjectInputStream$PeekInputStream.peek(ObjectInputStream.java:2296) 
    at java.io.ObjectInputStream$BlockDataInputStream.peek(ObjectInputStream.java:2589) 
    at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2599) 
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1319) 
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371) 
    at taraticketclienttest.TaraTicketClientTest.main(TaraTicketClientTest.java:37) 
BUILD SUCCESSFUL (total time: 0 seconds) 

這裏是我的客戶:

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

     try(Socket socket = new Socket("localhost", 7778)) { 

      ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); 
      ObjectInputStream in = new ObjectInputStream(socket.getInputStream()); 

      User u = new User("Wowa"); 

      out.writeObject(u); 

      User u2 = (User)in.readObject(); 

      System.out.println(u2.getName()); 


     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 

這裏是我的服務器:

public class DemoServer { 
public static void main(String[] args) throws ClassNotFoundException { 
    try(ServerSocket serverSocket = new ServerSocket(7778)) { 

     while (true) {     
      Socket clientSocket = serverSocket.accept(); 
      System.out.println("socket open..."); 

      ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream()); 
      ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream()); 

      User u = (User) in.readObject(); 

      System.out.println(u.getName()); 

      out.writeObject(u); 
     } 

    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 
} 

}

這是我的用戶:

public class User implements Serializable { 
private String name; 

public User(){} 

public User(String name){ 
    this.name = name; 
} 

public String getName(){ 
    return this.name; 
} 

}

+0

使用傑克遜美好的JSON對象序列化的詳細信息分析異常,最好只使用e.printStackTrace()來獲取包含所有信息的完整堆棧跟蹤。 – Andreas

回答

1

你需要你的User類來實現Serializable

public class User implements Serializable { 
    ... 
} 

對象不能writen到/除非它們實現Serializable

+0

看我的更新...我得到一個新的錯誤 – Tarasov

1

作爲一個從ObjectInputStreamObjectOutputStream閱讀另外,你可以通過u將對象作爲JSON格式的字符串發送唱歌JacksonBoon。他們肯定比defalut Java對象序列化更快(不需要使類序列化)

你可以在下面的鏈接 how-to-convert-java-object-to-from-json-jackson

+0

我必須閱讀這篇文章 – Tarasov

相關問題