1
1
package com .iluwatar .reactor .app ;
2
2
3
3
import java .io .IOException ;
4
+ import java .util .ArrayList ;
5
+ import java .util .List ;
4
6
5
7
import com .iluwatar .reactor .framework .AbstractNioChannel ;
6
8
import com .iluwatar .reactor .framework .ChannelHandler ;
9
+ import com .iluwatar .reactor .framework .Dispatcher ;
7
10
import com .iluwatar .reactor .framework .NioDatagramChannel ;
8
11
import com .iluwatar .reactor .framework .NioReactor ;
9
12
import com .iluwatar .reactor .framework .NioServerSocketChannel ;
64
67
public class App {
65
68
66
69
private NioReactor reactor ;
70
+ private List <AbstractNioChannel > channels = new ArrayList <>();
67
71
68
72
/**
69
73
* App entry.
70
74
*
71
75
* @throws IOException
72
76
*/
73
77
public static void main (String [] args ) throws IOException {
74
- new App ().start ();
78
+ new App ().start (new ThreadPoolDispatcher ( 2 ) );
75
79
}
76
80
77
81
/**
78
82
* Starts the NIO reactor.
83
+ * @param threadPoolDispatcher
79
84
*
80
85
* @throws IOException if any channel fails to bind.
81
86
*/
82
- public void start () throws IOException {
87
+ public void start (Dispatcher dispatcher ) throws IOException {
83
88
/*
84
89
* The application can customize its event dispatching mechanism.
85
90
*/
86
- reactor = new NioReactor (new ThreadPoolDispatcher ( 2 ) );
91
+ reactor = new NioReactor (dispatcher );
87
92
88
93
/*
89
94
* This represents application specific business logic that dispatcher will call on appropriate
@@ -103,20 +108,26 @@ public void start() throws IOException {
103
108
* Stops the NIO reactor. This is a blocking call.
104
109
*
105
110
* @throws InterruptedException if interrupted while stopping the reactor.
111
+ * @throws IOException if any I/O error occurs
106
112
*/
107
- public void stop () throws InterruptedException {
113
+ public void stop () throws InterruptedException , IOException {
108
114
reactor .stop ();
115
+ for (AbstractNioChannel channel : channels ) {
116
+ channel .getChannel ().close ();
117
+ }
109
118
}
110
119
111
- private static AbstractNioChannel tcpChannel (int port , ChannelHandler handler ) throws IOException {
120
+ private AbstractNioChannel tcpChannel (int port , ChannelHandler handler ) throws IOException {
112
121
NioServerSocketChannel channel = new NioServerSocketChannel (port , handler );
113
122
channel .bind ();
123
+ channels .add (channel );
114
124
return channel ;
115
125
}
116
126
117
- private static AbstractNioChannel udpChannel (int port , ChannelHandler handler ) throws IOException {
127
+ private AbstractNioChannel udpChannel (int port , ChannelHandler handler ) throws IOException {
118
128
NioDatagramChannel channel = new NioDatagramChannel (port , handler );
119
129
channel .bind ();
130
+ channels .add (channel );
120
131
return channel ;
121
132
}
122
133
}
0 commit comments