I'm trying to pass the person object that was instantiated on the server to the client. But I can not. Below are the classes I've used:
Server
public class ServidorTCPBasico {
public static void main(String[] args) {
try {
ServerSocket servidor = new ServerSocket(12345);
System.out.println("Servidor ouvindo a porta 12345");
while (true) {
Pessoa pessoa = new Pessoa("José", "Zé");
Socket cliente = servidor.accept();
System.out.println("Cliente conectado: " + cliente.getInetAddress().getHostAddress());
ObjectOutputStream saida = new ObjectOutputStream(cliente.getOutputStream());
saida.flush();
saida.writeObject(pessoa);
saida.close();
cliente.close();
}
} catch (Exception e) {
System.out.println("Erro: " + e.getMessage());
} finally {
}
}}
Customer
public class ClienteTCPBasico {
public static void main(String[] args) {
try {
Socket cliente = new Socket("127.0.0.1",12345);
ObjectInputStream entrada = new ObjectInputStream(cliente.getInputStream());
Pessoa pessoa = (Pessoa)entrada.readObject();
JOptionPane.showMessageDialog(null,"Dados da pessoa:" + pessoa.toString());
entrada.close();
System.out.println("Conexão encerrada");
}
catch(Exception e) {
System.out.println("Erro: " + e.getMessage());
}
}
}
Person Class
public class Pessoa {
String nome;
String apelido;
public Pessoa(String nome, String apelido) {
this.nome = nome;
this.apelido = apelido;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getApelido() {
return apelido;
}
public void setApelido(String apelido) {
this.apelido = apelido;
}
@Override
public String toString() {
return "Pessoa{" + "nome=" + nome + ", apelido=" + apelido + '}';
}
}
When I run the class ServidorTCPBasico
all OK, but when I run the class ClienteTCPBasico
it gives the following error:
Error: Connection reset
I used as an example to develop this code the article from DevMedia
I used the classes of the same name just replace the class Date with the Person class. I wanted to pass an object created by me using socket, but unfortunately it did not work! Where is there an error in this application?
I think the error is in using the class ObjectOutputStream
to read a non-primitive type, but I'm not sure.