-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClienteMulticast.java
More file actions
83 lines (72 loc) · 3.09 KB
/
ClienteMulticast.java
File metadata and controls
83 lines (72 loc) · 3.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Scanner;
public class ClienteMulticast {
private static final String GRUPO = "230.0.0.0";
private static final int avisos_gerais = 4321;
private static final int Atividades = 4323;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.print("Digite seu nome: ");
String nome = sc.nextLine();
System.out.println("Escolha o tópico:");
System.out.println("1 - Avisos Gerais");
System.out.println("2 - Atividades Extracurriculares");
System.out.println("3 - Ambos os tópicos");
System.out.print("Opção: ");
int opcao = Integer.parseInt(sc.nextLine());
enviarInscricao(nome);
switch (opcao) {
case 1:
receberMensagens(avisos_gerais, "Avisos Gerais");
break;
case 2:
receberMensagens(Atividades, "Atividades Extracurriculares");
break;
case 3:
new Thread(() -> receberMensagens(avisos_gerais, "Avisos Gerais")).start();
new Thread(() -> receberMensagens(Atividades, "Atividades Extracurriculares")).start();
break;
default:
System.out.println("Opção inválida!");
}
}
private static void enviarInscricao(String nome) throws IOException {
MulticastSocket socket = new MulticastSocket();
InetAddress grupo = InetAddress.getByName(GRUPO);
String dados = nome;
byte[] buffer = dados.getBytes();
DatagramPacket pacote = new DatagramPacket(buffer, buffer.length, grupo, 4322);
socket.send(pacote);
socket.close();
}
private static void receberMensagens(int porta, String topico) {
try {
MulticastSocket socket = new MulticastSocket(porta);
InetAddress grupo = InetAddress.getByName(GRUPO);
InetSocketAddress socketAddress = new InetSocketAddress(grupo, porta);
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(grupo);
socket.joinGroup(socketAddress, networkInterface);
limparConsole();
System.out.println("Escutando tópico: " + topico);
while (true) {
byte[] buffer = new byte[1024];
DatagramPacket pacote = new DatagramPacket(buffer, buffer.length);
socket.receive(pacote);
String mensagem = new String(pacote.getData(), 0, pacote.getLength());
System.out.println("[" + topico + "] " + mensagem);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void limparConsole() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
}