Boa noite!
Eu estou desenvolvendo um aplicativo desktop que permite que dois usuários possam se comunicar através de uma rede, porém quando o servidor está conectado na internet através de um roteador, eu não faço a mínima ideia de como referenciar o IP dele.
Segue abaixo o código do client e do servidor:
CLIENT:
[code]public class Cliente {
public static void main(String[] args) throws UnknownHostException,
IOException {
Scanner teclado = new Scanner(System.in);
PrintStream saida = null;
try {
Socket client = new Socket(“127.0.0.1”, 12345);
saida = new PrintStream(client.getOutputStream());
System.out.println("Digite o seu nick: ");
String nick = teclado.nextLine();
saida.println(nick);
System.out.println(nick + " acabou de se conectar! (Tecle Ctrl+Z para sair)");
Thread listen = new Thread(new Listener(client.getInputStream()));
listen.start();
while (teclado.hasNextLine()) {
saida.println(teclado.nextLine());
}
} catch (ConnectException e) {
System.out.println("Não foi possível se conectar ao servidor.");
} finally {
try {
saida.close();
teclado.close();
} catch (Exception e) {
}
}
}
}
class Listener implements Runnable {
Scanner in;
Listener(InputStream in) {
this.in = new Scanner(in);
}
public void run() {
while (in.hasNextLine()) {
System.out.println(in.nextLine());
}
}
}[/code]
SERVIDOR:
[code]public class Servidor {
public static void main(String[] args) throws IOException {
ServerSocket servidor = null;
try {
servidor = new ServerSocket(12345);
Set<ClientSession> clientList = new HashSet<ClientSession>();
Set<Thread> procList = new HashSet<Thread>();
System.out.println("Servidor iniciado!");
while (true) {
ClientSession client = new ClientSession(servidor.accept(),
clientList);
clientList.add(client);
Thread thrd = new Thread(client);
thrd.start();
procList.add(thrd);
}
} catch (ConnectException e) {
} finally {
servidor.close();
}
}
}
class ClientSession implements Runnable {
Socket client;
Scanner in;
PrintStream out;
String nick;
Set<ClientSession> list;
static String last = “”;
ClientSession(Socket client, Set<ClientSession> list) {
this.client = client;
this.list = list;
try {
in = new Scanner(client.getInputStream());
out = new PrintStream(client.getOutputStream());
nick = in.nextLine();
} catch (IOException e) {
e.printStackTrace();
}
}
synchronized boolean send(String sender, String message) {
if (!sender.equals(nick)) {
if (!ClientSession.last.equals(sender))
out.println(sender + " diz:");
out.println(" " + message);
ClientSession.last = sender;
return true;
}
return false;
}
public void run() {
System.out.println(" " + nick + " entrou na sala.");
while (in.hasNextLine()) {
String text = in.nextLine();
for (ClientSession client : list) {
client.send(nick, text);
}
}
try {
list.remove(this);
out.close();
in.close();
client.close();
System.out.println(" " + nick + " saiu da sala.");
} catch (IOException e) {
}
}
}[/code]