Project

General

Profile

Statistics
| Revision:

root / src / Channel.java

History | View | Annotate | Download (2.21 KB)

1 1 up20150487
import java.io.IOException;
2
import java.net.DatagramPacket;
3
import java.net.InetAddress;
4
import java.net.MulticastSocket;
5
import java.util.concurrent.ConcurrentHashMap;
6
7
import java.io.ByteArrayOutputStream;
8
9
public abstract class Channel extends Thread {
10
    public enum ChannelType {
11
        MC, MDB, MDR
12
    }
13
14
    protected InetAddress channelAdress;
15
    protected int port;
16
    protected int peerId;
17
    protected ChannelsInfo cInfo;
18
    protected MulticastSocket socket;
19
    protected ChannelType type;
20
21
    protected PeersInfo peersInfo;
22
23
24
    public Channel(PeersInfo peersInfo, ChannelsInfo cInfo, int id, InetAddress addr, int port) {
25
        this.peersInfo=peersInfo;
26
        this.peerId = id;
27
        this.channelAdress = addr;
28
        this.port = port;
29
        this.cInfo = cInfo;
30
    }
31
32
    public int getPort() {
33
        return port;
34
    }
35
36
    public void setPort(int porta) {
37
        this.port = porta;
38
    }
39
40
    public InetAddress getChannelAddress() {
41
        return channelAdress;
42
    }
43
44
    public MulticastSocket getSocket() {
45
        return this.socket;
46
    }
47
48
    public void setSocket(MulticastSocket socket) {
49
        this.socket = socket;
50
    }
51
52
    private void close() {
53
        try {
54
            this.socket.leaveGroup(this.channelAdress);
55
            this.socket.close();
56
        } catch (IOException e) {
57
            throw new RuntimeException("Socket couldn't be closed.", e);
58
        }
59
    }
60
61
    public byte[] createMessage(String protocol, String version, int senderId, String fileId, String[] args,
62
                                byte[] body) {
63
        String msg = "";
64
        msg = protocol + " " + version + " " + senderId + " " + fileId + " ";
65
        for (String arg : args) {
66
            msg += arg + " ";
67
        }
68
        msg += "\r\n\r\n";
69
        System.out.println(msg);
70
71
        ByteArrayOutputStream append = new ByteArrayOutputStream();
72
73
        try {
74
            append.write(msg.getBytes());
75
            if (body != null) {
76
                append.write(body);
77
            }
78
79
        } catch (IOException e) {
80
            e.printStackTrace();
81
        }
82
83
        return append.toByteArray();
84
85
    }
86
87
    @Override
88
    public void run() {
89
        System.out.println("The channel is now running.");
90
    }
91
92
}