Project

General

Profile

Statistics
| Revision:

root / src / Socket.java

History | View | Annotate | Download (2.09 KB)

1 3 up20160792
2
import java.io.IOException;
3
import java.net.DatagramPacket;
4
import java.net.InetAddress;
5
import java.net.MulticastSocket;
6
import java.util.AbstractMap.SimpleEntry;
7
8
public class Socket implements Runnable {
9
10
    public MulticastSocket socket;
11
    public int port;
12
    public InetAddress address;
13
14
    public enum Type {
15
        MC, MDB, MDR
16
    }
17
18
    public Type type;
19
20
    public Server peer;
21
22
    // Message size(safe size)
23
    public static final int MESSAGE_SIZE = 65500;
24
25
    // Default constructor
26
    public Socket(Server peer, Type type) throws IOException {
27
28
        this.peer = peer;
29
30
        switch (type) {
31
        case MC:
32
            this.port = 8000;
33
            this.address = InetAddress.getByName("224.0.0.1");
34
            break;
35
        case MDB:
36
            this.port = 8001;
37
            this.address = InetAddress.getByName("224.0.0.2");
38
            break;
39
        case MDR:
40
            this.port = 8002;
41
            this.address = InetAddress.getByName("224.0.0.3");
42
            break;
43
        default:
44
            return;
45
        }
46
47
        this.type = type;
48
        this.socket = new MulticastSocket(this.port);
49
        this.socket.joinGroup(address);
50
51
    }
52
53
    // Specific constructor
54
    public Socket(Server peer, Type type, int port, String address) throws IOException {
55
56
        this.peer = peer;
57
        this.type = type;
58
        this.port = port;
59
        this.address = InetAddress.getByName(address);
60
        this.socket = new MulticastSocket(this.port);
61
        this.socket.joinGroup(this.address);
62
63
    }
64
65
    @Override
66
    public void run() {
67
68
        while (true) {
69
70
            byte[] buf = new byte[MESSAGE_SIZE];
71
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
72
73
            try {
74
75
                this.socket.receive(packet);
76
77
                System.out.println("Packet received, launching interpreter");
78
79
                Server.pool.execute(new Interpreter(peer, packet));
80
81
            } catch (IOException e) {
82
                e.printStackTrace();
83
            }
84
85
        }
86
87
    }
88
89
}