summaryrefslogtreecommitdiffstats
path: root/src/main/java/derms/net/ConcurrentMulticastSocket.java
blob: 6aeb5a894ef2e0b5dc7d6d59e963e83430d52d03 (plain) (blame)
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
package derms.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.time.Duration;

public class ConcurrentMulticastSocket {
    private final MulticastSocket sock;

    /** Create a socket for sending. */
    public ConcurrentMulticastSocket() throws IOException {
        this.sock = new MulticastSocket();
    }

    /** Create a socket bound to the specified port for receiving. */
    public ConcurrentMulticastSocket(int port) throws IOException {
        this.sock = new MulticastSocket(port);
    }

    /** Join a multicast group. */
    public synchronized void joinGroup(InetAddress mcastaddr) throws IOException {
        sock.joinGroup(mcastaddr);
    }

    public synchronized void send(DatagramPacket p) throws IOException {
        sock.send(p);
    }

    public synchronized void receive(DatagramPacket p) throws IOException {
        sock.receive(p);
    }

    public synchronized void setSoTimeout(Duration timeout) throws SocketException {
        sock.setSoTimeout((int) timeout.toMillis());
    }

    public synchronized void close() {
        sock.close();
    }

    @Override
    public String toString() {
        return sock.getLocalSocketAddress().toString();
    }
}