m-chrzan.xyz
aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/pl/edu/mimuw/cloudatlas/agent/modules/UDUPClient.java
blob: 82aaeb1d100e129a1ce67413e1a4be330627ac72 (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
package pl.edu.mimuw.cloudatlas.agent.modules;

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

import java.io.IOException;
import java.net.*;

public class UDUPClient {
    private UDUP udp;
    private UDUPSerializer serializer;
    private int serverPort;
    private DatagramSocket socket;
    private int bufsize;

    UDUPClient(UDUP udp, int serverPort, int bufferSize) throws SocketException {
        this.udp = udp;
        this.serverPort = serverPort;
        this.socket = new DatagramSocket();
        this.bufsize = bufferSize;
        this.serializer = new UDUPSerializer();
    }

    public void sendMessage(UDUPMessage msg) throws IOException {
        int offset = 0;
        int outputSize;

        byte[] buf = this.serializer.serialize(msg);
        outputSize = buf.length;

        do {
            outputSize =- bufsize;
            offset += bufsize;
            DatagramPacket packet = new DatagramPacket(buf, buf.length, msg.getContact().getAddress(), this.serverPort);
            System.out.println("UDP sends message: ");
            for (byte b : buf) {
                System.out.print(b);
            }
            System.out.println("to " + packet.getAddress());
            this.socket.send(packet);
        } while (outputSize > bufsize);
    }

    void close() {
        this.socket.close();
    }

}