-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.java
97 lines (92 loc) · 2.96 KB
/
Main.java
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import javafx.util.Pair;
import java.io.IOException;
import java.net.*;
import java.util.HashSet;
import java.util.Scanner;
/*
class CountRunnable implements Runnable{
private MulticastSocket socket;
CountRunnable(MulticastSocket socket){
this.socket = socket;
}
public void run(){
try {
List<InterfaceAddress> list = socket.getNetworkInterface().getInterfaceAddresses();
System.out.println(1 + (list == null ? 0 : list.size()));
} catch (SocketException ignored) {
}
}
}
*/
class UpdateRunnable implements Runnable {
private MulticastSocket socket;
private int count = -1;
public void run() {
while (true){
try {
Thread.sleep(1000);
int size = Main.members.size();
if (count != size)
System.out.println(count = size);
Main.members.clear();
} catch (InterruptedException ignored) {
}
}
}
}
class SendRunnable implements Runnable{
private MulticastSocket socket;
private InetAddress group;
SendRunnable(MulticastSocket socket, InetAddress group){
this.socket = socket;
this.group = group;
}
public void run(){
try {
while (true){
DatagramPacket dg = new DatagramPacket(Main.DG.getBytes(), Main.DG.length(), group, Main.port);
socket.send(dg);
Thread.sleep(500);
}
} catch (InterruptedException | IOException ignored) {
}
}
}
class ListenRunnable implements Runnable{
private MulticastSocket socket;
ListenRunnable(MulticastSocket socket){
this.socket = socket;
}
public void run(){
byte[] buf = new byte[256];
DatagramPacket dg;
while (true) {
dg = new DatagramPacket(buf, buf.length);
try {
socket.receive(dg);
String s = new String(dg.getData(), 0, dg.getLength());
if (Main.DG.equals(s))
Main.members.add(new Pair<>(dg.getAddress(), dg.getPort()));
} catch (IOException ignored) {
}
}
}
}
public class Main
{
static HashSet<Pair<InetAddress, Integer>> members = new HashSet<>();
final static int port = 4446;
final static String DG = "0";
public static void main(String[] args) throws IOException{
MulticastSocket socket = new MulticastSocket(port);
InetAddress group = InetAddress.getByName(args[0]);
socket.joinGroup(group);
new Thread(new ListenRunnable(socket)).start();
new Thread(new SendRunnable(socket, group)).start();
new Thread(new UpdateRunnable()).start();
Scanner s = new Scanner(System.in);
while (!s.nextLine().equals("q"));
socket.leaveGroup(group);
System.exit(0);
}
}