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
|
package com.mavlushechka.notaryqueue.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.mavlushechka.notaryqueue.model.Client;
import java.io.IOException;
import java.net.*;
public class Socket {
private static final MulticastSocket NEW_CLIENT_SOCKET;
public static final int NEW_CLIENT_PORT = 1024;
private static final InetSocketAddress NEW_CLIENT_SOCKET_ADDRESS = new InetSocketAddress("228.5.6.7", NEW_CLIENT_PORT);
private static final MulticastSocket DELETED_CLIENT_SOCKET;
public static final int DELETED_CLIENT_PORT = 1025;
private static final InetSocketAddress DELETED_CLIENT_SOCKET_ADDRESS = new InetSocketAddress("228.5.6.7", DELETED_CLIENT_PORT);
public static final byte[] BUFFER = new byte[1024];
static {
try {
NEW_CLIENT_SOCKET = new MulticastSocket(NEW_CLIENT_PORT);
NEW_CLIENT_SOCKET.joinGroup(NEW_CLIENT_SOCKET_ADDRESS, null);
DELETED_CLIENT_SOCKET = new MulticastSocket(DELETED_CLIENT_PORT);
DELETED_CLIENT_SOCKET.joinGroup(DELETED_CLIENT_SOCKET_ADDRESS, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void sendNewClient(Client client) {
send(client, NEW_CLIENT_SOCKET, NEW_CLIENT_SOCKET_ADDRESS, NEW_CLIENT_PORT);
}
public static void sendDeletedClient(Client client) {
send(client, DELETED_CLIENT_SOCKET, DELETED_CLIENT_SOCKET_ADDRESS, DELETED_CLIENT_PORT);
}
public static Client receiveNewClient() {
return receiveClient(NEW_CLIENT_SOCKET);
}
public static Client receiveDeletedClient() {
return receiveClient(DELETED_CLIENT_SOCKET);
}
private static void send(Client client, MulticastSocket multicastSocket, InetSocketAddress inetSocketAddress, int port) {
try {
multicastSocket.send(new DatagramPacket(new ObjectMapper().registerModule(new JavaTimeModule()).writeValueAsString(client).getBytes(), new ObjectMapper().registerModule(new JavaTimeModule()).writeValueAsString(client).getBytes().length, inetSocketAddress.getAddress(), port));
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
private static Client receiveClient(MulticastSocket multicastSocket) {
Client client = null;
while (client == null) {
DatagramPacket datagramPacket = new DatagramPacket(BUFFER, BUFFER.length);
try {
multicastSocket.receive(datagramPacket);
client = new ObjectMapper().registerModule(new JavaTimeModule()).readValue(datagramPacket.getData(), Client.class);
System.out.println(client + " is received.");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return client;
}
}
|