I would like to send data between different machines, between 2 computers, between a computer and an Android .
I made the example internally, on the same computer, but when I disconnect (the server stays on one computer and the client goes to another one, it does not work).
Server:
public static void main(String[] args) {
try {
// Instancia o ServerSocket ouvindo a porta 12345
ServerSocket servidor = new ServerSocket(12345);
System.out.println("Servidor ouvindo a porta 12345");
// servidor.bind(new InetSocketAddress("192.168.5.1", 0));
InetAddress inet = servidor.getInetAddress();
System.out.println("HostAddress="+inet.getHostAddress());
System.out.println("HostName="+inet.getHostName());
while(true) {
// o método accept() bloqueia a execução até que
// o servidor receba um pedido de conexão
Socket cliente = servidor.accept();
System.out.println("Cliente conectado: " + cliente.getInetAddress().getHostAddress());
ObjectOutputStream saida = new ObjectOutputStream(cliente.getOutputStream());
saida.flush();
saida.writeObject(new Date());
saida.close();
cliente.close();
}
}
catch(Exception e) {
System.out.println("Erro: " + e.getMessage());
}
}
Client:
public static void main(String[] args) {
try {
Socket cliente = new Socket("0.0.0.0",12345);
InetAddress inet = cliente.getInetAddress();
System.out.println("HostAddress="+inet.getHostAddress());
System.out.println("HostName="+inet.getHostName());
ObjectInputStream entrada = new ObjectInputStream(cliente.getInputStream());
Date data_atual = (Date)entrada.readObject();
JOptionPane.showMessageDialog(null,"Data recebida do servidor:" + data_atual.toString());
entrada.close();
System.out.println("Conexão encerrada");
}
catch(Exception e) {
System.out.println("Erro: " + e.getMessage());
}
}
The strange thing is that the server output is:
Servidor ouvindo a porta 12345
HostAddress=0.0.0.0
HostName=0.0.0.0
Then when I try to put the client on another computer it does not work, even if I insert the IP where the server is.
Note: The machines are on different networks.
Obs :