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; } }