I created a chat in Java. In the Servidor
class, the user passes as input the port on which the server will roam. In order for the chat to work correctly, I need to access this variable of class Cliente
, passing it as a parameter so the client can connect to the server.
But I'm not able to access it, I try to create a new server, but it does not work. It was the only way I thought of accessing, but I think it would be wrong, since the server is already created inside the class itself.
public class Servidor {
private Scanner scan = new Scanner(System.in);
private ServerSocket servidor;
private int numero_porta;
public static void main(String args[]) throws IOException {
new Servidor().iniciarServidor();
}
public int pegarPorta(){
System.out.print("Digite a porta: ");
numero_porta = scan.nextInt();
return numero_porta;
}
public int getNumero_porta() {
return this.numero_porta;
}
public void iniciarServidor() throws IOException {
servidor = new ServerSocket(numero_porta);
System.out.println("Servidor rodando na porta " + pegarPorta());
}
public class Cliente {
private int porta;
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
Socket socket;
String nome;
Servidor server = new Servidor();
String endereco;
System.out.print("Digite um endereco IP: ");
endereco = scan.nextLine();
socket = new Socket(endereco, server.getNumero_porta());
}