Skip to content

Commit b7b396a

Browse files
committed
added idle channel closer
1 parent 7daa0e8 commit b7b396a

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package net.sharksystem.streams;
2+
3+
import net.sharksystem.utils.AlarmClock;
4+
import net.sharksystem.utils.AlarmClockListener;
5+
6+
import java.io.IOException;
7+
8+
public class IdleStreamPairCloser implements AlarmClockListener, WrappedStreamPairListener {
9+
private final int timeout;
10+
private StreamPairWrapper streamPairWrapper;
11+
private AlarmClock alarmClock;
12+
13+
private IdleStreamPairCloser(int timeout) {
14+
this.timeout = timeout;
15+
}
16+
17+
public static IdleStreamPairCloser getIdleStreamsCloser(StreamPair streamPair, int timeout) throws IOException {
18+
// create object that also becomes listener
19+
IdleStreamPairCloser idleStreamPairCloser = new IdleStreamPairCloser(timeout);
20+
21+
// create wrapper with listener
22+
StreamPairWrapper streamPairWrapper = new StreamPairWrapper(
23+
streamPair.getInputStream(), streamPair.getOutputStream(), idleStreamPairCloser, "X");
24+
25+
// now: put wrapper into listener
26+
idleStreamPairCloser.setStreamPairWrapper(streamPairWrapper);
27+
return idleStreamPairCloser;
28+
}
29+
30+
void setStreamPairWrapper(StreamPairWrapper streamPairWrapper) {
31+
this.streamPairWrapper = streamPairWrapper;
32+
}
33+
34+
public void start() {
35+
this.alarmClock = new AlarmClock(this.timeout, this);
36+
}
37+
38+
@Override
39+
public void alarmClockRinging(int i) {
40+
try {
41+
this.streamPairWrapper.getInputStream().close();
42+
} catch (IOException e) {
43+
// ignore
44+
}
45+
}
46+
47+
@Override
48+
public void notifyClosed(StreamPair streamPair, String s) {
49+
this.alarmClock.kill(); // nothing todo.
50+
this.alarmClock = null;
51+
}
52+
53+
@Override
54+
public void notifyAction(String s) {
55+
if(alarmClock != null) {
56+
this.alarmClock.kill();
57+
this.alarmClock = new AlarmClock(timeout, this);
58+
} // else not yet started
59+
}
60+
}

0 commit comments

Comments
 (0)