11package com .iluwatar .reactor .app ;
22
33import java .io .IOException ;
4+ import java .util .ArrayList ;
5+ import java .util .List ;
46
57import com .iluwatar .reactor .framework .AbstractNioChannel ;
68import com .iluwatar .reactor .framework .ChannelHandler ;
9+ import com .iluwatar .reactor .framework .Dispatcher ;
710import com .iluwatar .reactor .framework .NioDatagramChannel ;
811import com .iluwatar .reactor .framework .NioReactor ;
912import com .iluwatar .reactor .framework .NioServerSocketChannel ;
6467public class App {
6568
6669 private NioReactor reactor ;
70+ private List <AbstractNioChannel > channels = new ArrayList <>();
6771
6872 /**
6973 * App entry.
7074 *
7175 * @throws IOException
7276 */
7377 public static void main (String [] args ) throws IOException {
74- new App ().start ();
78+ new App ().start (new ThreadPoolDispatcher ( 2 ) );
7579 }
7680
7781 /**
7882 * Starts the NIO reactor.
83+ * @param threadPoolDispatcher
7984 *
8085 * @throws IOException if any channel fails to bind.
8186 */
82- public void start () throws IOException {
87+ public void start (Dispatcher dispatcher ) throws IOException {
8388 /*
8489 * The application can customize its event dispatching mechanism.
8590 */
86- reactor = new NioReactor (new ThreadPoolDispatcher ( 2 ) );
91+ reactor = new NioReactor (dispatcher );
8792
8893 /*
8994 * This represents application specific business logic that dispatcher will call on appropriate
@@ -103,20 +108,26 @@ public void start() throws IOException {
103108 * Stops the NIO reactor. This is a blocking call.
104109 *
105110 * @throws InterruptedException if interrupted while stopping the reactor.
111+ * @throws IOException if any I/O error occurs
106112 */
107- public void stop () throws InterruptedException {
113+ public void stop () throws InterruptedException , IOException {
108114 reactor .stop ();
115+ for (AbstractNioChannel channel : channels ) {
116+ channel .getChannel ().close ();
117+ }
109118 }
110119
111- private static AbstractNioChannel tcpChannel (int port , ChannelHandler handler ) throws IOException {
120+ private AbstractNioChannel tcpChannel (int port , ChannelHandler handler ) throws IOException {
112121 NioServerSocketChannel channel = new NioServerSocketChannel (port , handler );
113122 channel .bind ();
123+ channels .add (channel );
114124 return channel ;
115125 }
116126
117- private static AbstractNioChannel udpChannel (int port , ChannelHandler handler ) throws IOException {
127+ private AbstractNioChannel udpChannel (int port , ChannelHandler handler ) throws IOException {
118128 NioDatagramChannel channel = new NioDatagramChannel (port , handler );
119129 channel .bind ();
130+ channels .add (channel );
120131 return channel ;
121132 }
122133}
0 commit comments