forked from inesxferreira/SD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Demultiplexer.java
229 lines (210 loc) · 5.6 KB
/
Demultiplexer.java
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Demultiplexer implements AutoCloseable {
private Connection connection;
private Map<Integer, DataQueue> map = new HashMap<>();
private ReentrantLock maplock = new ReentrantLock();
private boolean exception;
public Demultiplexer(Connection conn) {
this.connection = conn;
exception = true;
}
public Connection getConnection() {
return connection;
}
public class DataQueue {
ReentrantLock l;
Condition cond;
Queue<byte[]> queue;
public DataQueue() { // listas para guardar as mensagens
l = new ReentrantLock();
cond = l.newCondition();
queue = new ArrayDeque<>();
}
public void addToQueue(byte[] data) {
l.lock();
queue.add(data);
l.unlock();
}
public void queueCondSignal() {
cond.signal();
}
public void queueLock() {
l.lock();
}
public void queueUnlock() {
l.unlock();
}
}
public void endAll() {
for (DataQueue q : map.values()) {
q.queueLock();
q.cond.signalAll();
q.queueUnlock();
}
}
public void start() {
new Thread(() -> {
Pdu frame = null;
while (true) {
try {
frame = connection.receive();
} catch (IOException e) {
exception = false;
endAll();
System.exit(0);
}
maplock.lock();
if (!map.containsKey(frame.tag))
map.put(frame.tag, new DataQueue());
DataQueue currqueue = map.get(frame.tag);
currqueue.queueLock();
currqueue.addToQueue(frame.data);
maplock.unlock();
currqueue.queueCondSignal();
currqueue.queueUnlock();
}
}).start();
}
public void send(Pdu frame) throws IOException {
connection.send(frame);
}
public void send(int tag, String nome, byte[] data) throws IOException {
connection.send(tag, nome, data);
}
public byte[] receive(int tag) throws IOException, InterruptedException {
maplock.lock();
if (!map.containsKey(tag))
map.put(tag, new DataQueue());
DataQueue currqueue = map.get(tag);
maplock.unlock();
try {
currqueue.l.lock();
while (currqueue.queue.size() == 0 && exception) {
currqueue.cond.await();
}
if (!exception)
throw new IOException();
return currqueue.queue.remove();
} finally {
currqueue.l.unlock();
}
}
public void close() throws IOException {
connection.close();
}
}
/*
* public class Demultiplexer implements AutoCloseable {
* private final Connection tcon;
* private final Lock lock = new ReentrantLock();
* private final Map<Integer, Entry> buf = new HashMap<>();
* private Exception exception = null;
*
* private class Entry {
*
* // listas para guardar
* //mostra o teu codigo
* ReentrantLock l;
* Queue<byte[]> queue = new ArrayDeque<>();
* Condition cond = l.newCondition();
* }
*
* public Demultiplexer(Connection conn) {
* this.tcon = conn;
*
* }
*
* /*
* distribuidor
* espera que haja dados na conexão
* adiciona dados à fila
*/
/*
* public void start() {
* // "entrega", não distribui
* new Thread(() -> {
* try {
* while (true) {
* Pdu pduMessage = tcon.receive();
* lock.lock();
* try {
* if (!buf.containsKey(pduMessage.tag))
* buf.put(pduMessage.tag, new Entry());
* Entry e = buf.get(pduMessage.tag);
* if (e == null) { // se não tem nnh frame cria uma
* e = new Entry();
* buf.put(pduMessage.tag, e);
* }
* e.queue.add(pduMessage.data);
* e.cond.signal();
*
* } finally {
* lock.unlock();
*
* // TODO: handle exception
* }
* }
*
* } catch (Exception e) {
* exception = e;
* // TODO: handle exception
* }
* }).start();
*
* }
*
* public void send(Pdu pduMessage) throws IOException {
* tcon.send(pduMessage);
*
* }
*
* public void send(int tag, String email, byte[] data) throws IOException {
* // invocaçao direta da tagged connection, não espera em filas ao contrario do
* // receive
* // para a mesma conexão
* tcon.send(tag, email, data);
*
* }
*
* public byte[] receive(int tag) throws Exception {
* // recebe das filas, tira das filas
* // so olha para a fila, se nao existir items/mensagens espera. Não le socket
* lock.lock();// pq vamos mexer no map
* try {
* if (!buf.containsKey(tag))
* buf.put(tag, new Entry());
* Entry e = buf.get(tag);
* while (e.queue.isEmpty() && exception != null) {
* e.cond.wait(); // SINALIZAR quando ha alteraçoes de estado,erros
*
* }
* if (!e.queue.isEmpty()) {
* return e.queue.poll();// olhar para a fila e assim que a primeira mensagem
* for recebida tira
* /*
* poll-retorna o elemento da head da Queue. retorna null quando Queue is empty.
*/ /*
* } else { // ultima coisa que deve receber quando existem dados
* throw new Exception();
* }
*
* } finally {
* lock.unlock();
*
* }
* }
*
* @Override
* public void close() throws Exception {
* tcon.close();
*
* }
*
* }
*/