您好,我想用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;
}
}
使用傑克遜美好的JSON對象序列化的詳細信息分析異常,最好只使用e.printStackTrace()來獲取包含所有信息的完整堆棧跟蹤。 – Andreas