m-chrzan.xyz
aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/pl/edu/mimuw/cloudatlas/agent/modules/UDUP.java
blob: 501c76e16d2260714541ddc7c36bbec041dd6665 (plain)
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
package pl.edu.mimuw.cloudatlas.agent.modules;

import pl.edu.mimuw.cloudatlas.agent.messages.UDUPMessage;

import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Communication over UDP
 *
 * Client-server exchange pattern:
 *  server: init message
 *  client: ack message
 *
 *  retry count
 *  retry timeout after which retry happens
 **
 *  udp sends initiator module success/failure information
 *
 *  we have udps on different addresses with the same ports
 *  due to ValueContact design
 */

public class UDUP extends Module {
    private UDUPClient client;
    private UDUPServer server;

    public UDUP(int serverPort,
                int timeout,
                int bufferSize,
                UDUPServer server) {
        super(ModuleType.UDP);
        try {
            this.client = new UDUPClient(this, serverPort, bufferSize);
            this.server = server;
            this.server.setUDUP(this);
        } catch (SocketException e) {
            e.printStackTrace();
            this.client.close();
            this.server.close();
        }
    }

    public UDUPServer getServer() {
        return this.server;
    }

    public void handleTyped(UDUPMessage event) throws InterruptedException {
        System.out.println("UDP sending message " + event.getContent().getMessageId());
        try {
            this.client.sendMessage(event);
        } catch (IOException e) {
            System.out.println("UDP send message failed");
            e.printStackTrace();
        }
    }
}