Hi i want test a connection between Client and Server in Java. For Example I want to send a object from client to Server. The object is a User that I built.
If I start the Server and the Client I get this error:
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)
Here is my Client:
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();
}
}
Here is my Server:
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();
}
}
}
Here is my User:
public class User implements Serializable {
private String name;
public User(){}
public User(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
You need your class
User
to implementSerializable
:Objects can not be writen to / read from
ObjectInputStream
orObjectOutputStream
unless they implementSerializable