Project

General

Profile

Statistics
| Revision:

sdis1819-t7g02 / protocols / SendChunkMessageProtocol.java

History | View | Annotate | Download (1.22 KB)

1 1 up20150366
package protocols;
2
3
import java.util.Random;
4
5
import channels.Message;
6
import channels.MessageHeader;
7
import service.Chunk;
8
import service.Cloud;
9
import service.Constants;
10
11
public class SendChunkMessageProtocol extends Thread {
12
13
        Cloud father;
14
        Chunk toSend;
15
16
        public SendChunkMessageProtocol (Chunk c, Cloud f) {
17
                father = f;
18
                toSend = c;
19
        }
20
21
        @Override
22
        public void run() {
23
                String[] headerElements = new String[Constants.CHUNK_N_ARGS];
24
                Message m;
25
                MessageHeader h;
26
27
                headerElements[0] = Constants.CHUNK;
28
                    headerElements[1] = father.getProtocolVersion();
29
                    headerElements[2] = Integer.toString(father.getID());
30
                    headerElements[3] = toSend.getChunkId();
31
                    headerElements[4] = toSend.getChunkNumber();
32
33
                    try {
34
                            h = new MessageHeader(headerElements.clone());
35
36
                            m = new Message(h, toSend.getChunkContent());
37
38
                            waitRandomTime();
39
40
                        father.restoreCh.sendMessage(m);
41
                } catch (InterruptedException e) {
42
                        System.out.println("Error in send message protocol -> " + e.getMessage());
43
                }
44
        }
45
46
        public void waitRandomTime() throws InterruptedException {
47
                Random r = new Random();
48
                int low = 1;
49
                int high = 401;
50
                int result = r.nextInt(high-low) + low;
51
52
                Thread.sleep(result);
53
        }
54
}