View Javadoc

1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package org.jboss.netty.example.qotm;
17  
18  import java.net.InetSocketAddress;
19  import java.util.concurrent.Executors;
20  
21  import org.jboss.netty.bootstrap.ConnectionlessBootstrap;
22  import org.jboss.netty.channel.ChannelPipeline;
23  import org.jboss.netty.channel.ChannelPipelineFactory;
24  import org.jboss.netty.channel.Channels;
25  import org.jboss.netty.channel.FixedReceiveBufferSizePredictorFactory;
26  import org.jboss.netty.channel.socket.DatagramChannel;
27  import org.jboss.netty.channel.socket.DatagramChannelFactory;
28  import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory;
29  import org.jboss.netty.handler.codec.string.StringDecoder;
30  import org.jboss.netty.handler.codec.string.StringEncoder;
31  import org.jboss.netty.util.CharsetUtil;
32  
33  /**
34   * A UDP broadcast client that asks for a quote of the moment (QOTM) to
35   * {@link QuoteOfTheMomentServer}.
36   *
37   * Inspired by <a href="http://goo.gl/BsXVR">the official Java tutorial</a>.
38   */
39  public class QuoteOfTheMomentClient {
40  
41      private final int port;
42  
43      public QuoteOfTheMomentClient(int port) {
44          this.port = port;
45      }
46  
47      public void run() {
48          DatagramChannelFactory f =
49              new NioDatagramChannelFactory(Executors.newCachedThreadPool());
50  
51          ConnectionlessBootstrap b = new ConnectionlessBootstrap(f);
52  
53          // Configure the pipeline factory.
54          b.setPipelineFactory(new ChannelPipelineFactory() {
55              public ChannelPipeline getPipeline() throws Exception {
56                  return Channels.pipeline(
57                          new StringEncoder(CharsetUtil.ISO_8859_1),
58                          new StringDecoder(CharsetUtil.ISO_8859_1),
59                          new QuoteOfTheMomentClientHandler());
60              }
61          });
62  
63          // Enable broadcast
64          b.setOption("broadcast", "true");
65  
66          // Allow packets as large as up to 1024 bytes (default is 768).
67          // You could increase or decrease this value to avoid truncated packets
68          // or to improve memory footprint respectively.
69          //
70          // Please also note that a large UDP packet might be truncated or
71          // dropped by your router no matter how you configured this option.
72          // In UDP, a packet is truncated or dropped if it is larger than a
73          // certain size, depending on router configuration.  IPv4 routers
74          // truncate and IPv6 routers drop a large packet.  That's why it is
75          // safe to send small packets in UDP.
76          b.setOption(
77                  "receiveBufferSizePredictorFactory",
78                  new FixedReceiveBufferSizePredictorFactory(1024));
79  
80          DatagramChannel c = (DatagramChannel) b.bind(new InetSocketAddress(0));
81  
82          // Broadcast the QOTM request to port 8080.
83          c.write("QOTM?", new InetSocketAddress("255.255.255.255", port));
84  
85          // QuoteOfTheMomentClientHandler will close the DatagramChannel when a
86          // response is received.  If the channel is not closed within 5 seconds,
87          // print an error message and quit.
88          if (!c.getCloseFuture().awaitUninterruptibly(5000)) {
89              System.err.println("QOTM request timed out.");
90              c.close().awaitUninterruptibly();
91          }
92  
93          f.releaseExternalResources();
94      }
95  
96      public static void main(String[] args) throws Exception {
97          int port;
98          if (args.length > 0) {
99              port = Integer.parseInt(args[0]);
100         } else {
101             port = 8080;
102         }
103         new QuoteOfTheMomentClient(port).run();
104     }
105 }