0
I would like to send data between different machines, between two computers, between a computer and a Android for example.
I did the example internally, on the same computer, but when I separate (the server stays on one computer and the client goes to another. It doesn’t 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 in another computer it does not work, even if inserting (in the client) the IP where the server is.
Obs.: The machines are in different networks.
Obs².: I even tested with the firewall of Windows deactivated and did not work.
I had replaced by the ip of the machine where the server is but it didn’t work.
– Beto