Examples of ConnectionlessBootstrap


Examples of io.netty.bootstrap.ConnectionlessBootstrap

    public void run() {
        DatagramChannelFactory f =
            new NioDatagramChannelFactory(Executors.newCachedThreadPool());

        ConnectionlessBootstrap b = new ConnectionlessBootstrap(f);

        // Configure the pipeline factory.
        b.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(
                        new StringEncoder(CharsetUtil.ISO_8859_1),
                        new StringDecoder(CharsetUtil.ISO_8859_1),
                        new QuoteOfTheMomentClientHandler());
            }
        });

        // Enable broadcast
        b.setOption("broadcast", "true");

        // Allow packets as large as up to 1024 bytes (default is 768).
        // You could increase or decrease this value to avoid truncated packets
        // or to improve memory footprint respectively.
        //
        // Please also note that a large UDP packet might be truncated or
        // dropped by your router no matter how you configured this option.
        // In UDP, a packet is truncated or dropped if it is larger than a
        // certain size, depending on router configuration.  IPv4 routers
        // truncate and IPv6 routers drop a large packet.  That's why it is
        // safe to send small packets in UDP.
        b.setOption(
                "receiveBufferSizePredictorFactory",
                new FixedReceiveBufferSizePredictorFactory(1024));

        DatagramChannel c = (DatagramChannel) b.bind(new InetSocketAddress(0));

        // Broadcast the QOTM request to port 8080.
        c.write("QOTM?", new InetSocketAddress("255.255.255.255", port));

        // QuoteOfTheMomentClientHandler will close the DatagramChannel when a
View Full Code Here

Examples of org.jboss.netty.bootstrap.ConnectionlessBootstrap

  {
      id = String.format("%1$020d", Math.abs(new Random(System.currentTimeMillis()).nextLong())).getBytes();
      DatagramChannelFactory datagramChannelFactory = new
          OioDatagramChannelFactory(executor);

           connectionlessBootstrap = new
          ConnectionlessBootstrap(datagramChannelFactory);
          connectionlessBootstrap.setOption("broadcast", true);
          connectionlessBootstrap.setPipelineFactory(factory);
          datagramChannel = (DatagramChannel)
          connectionlessBootstrap.bind(new InetSocketAddress(mcastGroupPort));
View Full Code Here

Examples of org.jboss.netty.bootstrap.ConnectionlessBootstrap

    /**
     * {@inheritDoc}
     */
    public void start(int port) throws IOException {
        factory = new NioDatagramChannelFactory();
        ConnectionlessBootstrap bootstrap = new ConnectionlessBootstrap(factory);
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(new SimpleChannelUpstreamHandler() {
                    @Override
                    public void childChannelOpen(ChannelHandlerContext ctx, ChildChannelStateEvent e) throws Exception {
                        System.out.println("childChannelOpen");
                        setAttribute(ctx, STATE_ATTRIBUTE, State.WAIT_FOR_FIRST_BYTE_LENGTH);
                    }

                    @Override
                    public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
                        System.out.println("channelOpen");
                        setAttribute(ctx, STATE_ATTRIBUTE, State.WAIT_FOR_FIRST_BYTE_LENGTH);
                        allChannels.add(ctx.getChannel());
                    }

                    @Override
                    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
                        if (e.getMessage() instanceof ChannelBuffer) {
                            ChannelBuffer buffer = (ChannelBuffer) e.getMessage();

                            State state = (State) getAttribute(ctx, STATE_ATTRIBUTE);
                            int length = 0;
                            if (getAttributesMap(ctx).containsKey(LENGTH_ATTRIBUTE)) {
                                length = (Integer) getAttribute(ctx, LENGTH_ATTRIBUTE);
                            }
                            while (buffer.readableBytes() > 0) {
                                switch (state) {
                                case WAIT_FOR_FIRST_BYTE_LENGTH:
                                    length = (buffer.readByte() & 255) << 24;
                                    state = State.WAIT_FOR_SECOND_BYTE_LENGTH;
                                    break;
                                case WAIT_FOR_SECOND_BYTE_LENGTH:
                                    length += (buffer.readByte() & 255) << 16;
                                    state = State.WAIT_FOR_THIRD_BYTE_LENGTH;
                                    break;
                                case WAIT_FOR_THIRD_BYTE_LENGTH:
                                    length += (buffer.readByte() & 255) << 8;
                                    state = State.WAIT_FOR_FOURTH_BYTE_LENGTH;
                                    break;
                                case WAIT_FOR_FOURTH_BYTE_LENGTH:
                                    length += (buffer.readByte() & 255);
                                    state = State.READING;
                                    if ((length == 0) && (buffer.readableBytes() == 0)) {
                                        ctx.getChannel().write(ACK.slice());
                                        state = State.WAIT_FOR_FIRST_BYTE_LENGTH;
                                    }
                                    break;
                                case READING:
                                    int remaining = buffer.readableBytes();
                                    if (length > remaining) {
                                        length -= remaining;
                                        buffer.skipBytes(remaining);
                                    } else {
                                        buffer.skipBytes(length);
                                        SocketAddress remoteAddress = e.getRemoteAddress();
                                        ctx.getChannel().write(ACK.slice(), remoteAddress);
                                        state = State.WAIT_FOR_FIRST_BYTE_LENGTH;
                                        length = 0;
                                    }
                                }
                            }
                            setAttribute(ctx, STATE_ATTRIBUTE, state);
                            setAttribute(ctx, LENGTH_ATTRIBUTE, length);
                        }
                    }

                    @Override
                    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
                        allChannels.remove(ctx.getChannel());
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
                        e.getCause().printStackTrace();
                    }
                });
            }
        });
        allChannels.add(bootstrap.bind(new InetSocketAddress(port)));
    }
View Full Code Here

Examples of org.jboss.netty.bootstrap.ConnectionlessBootstrap

    /**
     * {@inheritedDoc}
     */
    public void start(final int port, final CountDownLatch counter, final byte[] data) throws IOException {
        factory = new NioDatagramChannelFactory();
        ConnectionlessBootstrap bootstrap = new ConnectionlessBootstrap(factory);
        bootstrap.setOption("sendBufferSize", 65536);
        bootstrap.setOption("receiveBufferSizePredictorFactory", new FixedReceiveBufferSizePredictorFactory(9000));
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(new SimpleChannelUpstreamHandler() {
                    private void sendMessage(ChannelHandlerContext ctx, byte[] data) {
                        ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(data);
                        ctx.getChannel().write(buffer);
                    }

                    @Override
                    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
                        if (e.getMessage() instanceof ChannelBuffer) {
                            ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
                            for (int i = 0; i < buffer.readableBytes(); ++i) {
                                counter.countDown();
                                if (counter.getCount() > 0) {
                                    sendMessage(ctx, data);
                                } else {
                                    ctx.getChannel().close();
                                }
                            }
                        } else {
                            throw new IllegalArgumentException(e.getMessage().getClass().getName());
                        }
                    }

                    @Override
                    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
                        sendMessage(ctx, data);
                    }

                });
            }
        });
        bootstrap.connect(new InetSocketAddress(port));
    }
View Full Code Here

Examples of org.jboss.netty.bootstrap.ConnectionlessBootstrap

  }

  @Override
  public void start() {
    // setup Netty server
    ConnectionlessBootstrap serverBootstrap = new ConnectionlessBootstrap
        (new OioDatagramChannelFactory(Executors.newCachedThreadPool()));
    final syslogHandler handler = new syslogHandler();
    handler.setFormater(formaterProp);
    handler.setKeepFields(keepFields);
    serverBootstrap.setOption("receiveBufferSizePredictorFactory",
      new AdaptiveReceiveBufferSizePredictorFactory(DEFAULT_MIN_SIZE,
        DEFAULT_INITIAL_SIZE, maxsize));
    serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
      @Override
      public ChannelPipeline getPipeline() {
       return Channels.pipeline(handler);
      }
     });

    if (host == null) {
      nettyChannel = serverBootstrap.bind(new InetSocketAddress(port));
    } else {
      nettyChannel = serverBootstrap.bind(new InetSocketAddress(host, port));
    }

    super.start();
  }
View Full Code Here

Examples of org.jboss.netty.bootstrap.ConnectionlessBootstrap

   * @return open data-gram channel
   */
  private Channel createRtpChannel(final SocketAddress local, final SocketAddress remote, final RaopRtpChannelType channelType)
  {
    /* Create bootstrap helper for a data-gram socket using NIO */
    final ConnectionlessBootstrap bootstrap = new ConnectionlessBootstrap(new NioDatagramChannelFactory(m_rtpExecutorService));
   
    /* Set the buffer size predictor to 1500 bytes to ensure that
     * received packets will fit into the buffer. Packets are
     * truncated if they are larger than that!
     */
    bootstrap.setOption("receiveBufferSizePredictorFactory", new FixedReceiveBufferSizePredictorFactory(1500));
   
    /* Set the socket's receive buffer size. We set it to 1MB */
    bootstrap.setOption("receiveBufferSize", 1024*1024);
   
    /* Set pipeline factory for the RTP channel */
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
      @Override
      public ChannelPipeline getPipeline() throws Exception {
        final ChannelPipeline pipeline = Channels.pipeline();

        pipeline.addLast("executionHandler", AirReceiver.ChannelExecutionHandler);
        pipeline.addLast("exceptionLogger", m_exceptionLoggingHandler);
        pipeline.addLast("decoder", m_decodeHandler);
        pipeline.addLast("encoder", m_encodeHandler);
        /* We pretend that all communication takes place on the audio channel,
         * and simply re-route packets from and to the control and timing channels
         */
        if (!channelType.equals(RaopRtpChannelType.Audio)) {
          pipeline.addLast("inputToAudioRouter", m_inputToAudioRouterDownstreamHandler);
          /* Must come *after* the router, otherwise incoming packets are logged twice */
          pipeline.addLast("packetLogger", m_packetLoggingHandler);
        }
        else {
          /* Must come *before* the router, otherwise outgoing packets are logged twice */
          pipeline.addLast("packetLogger", m_packetLoggingHandler);
          pipeline.addLast("audioToOutputRouter", m_audioToOutputRouterUpstreamHandler);
          pipeline.addLast("timing", m_timingHandler);
          pipeline.addLast("resendRequester", m_resendRequestHandler);
          if (m_decryptionHandler != null)
            pipeline.addLast("decrypt", m_decryptionHandler);
          if (m_audioDecodeHandler != null)
            pipeline.addLast("audioDecode", m_audioDecodeHandler);
          pipeline.addLast("enqueue", m_audioEnqueueHandler);
        }

        return pipeline;
      }
    });

    Channel channel = null;
    boolean didThrow = true;
    try {
      /* Bind to local address */
      channel = bootstrap.bind(local);
     
      /* Add to group of RTP channels beloging to this RTSP connection */
      m_rtpChannels.add(channel);
 
      /* Connect to remote address if one was provided */
 
View Full Code Here

Examples of org.jboss.netty.bootstrap.ConnectionlessBootstrap

                        new Object[]{configuration.getHost(), configuration.getPort(), clientBootstrap.getOptions()});
            }
            return answer;
        } else {
            // its okay to create a new bootstrap for each new channel
            ConnectionlessBootstrap connectionlessClientBootstrap = new ConnectionlessBootstrap(datagramChannelFactory);
            connectionlessClientBootstrap.setOption("child.keepAlive", configuration.isKeepAlive());
            connectionlessClientBootstrap.setOption("child.tcpNoDelay", configuration.isTcpNoDelay());
            connectionlessClientBootstrap.setOption("child.reuseAddress", configuration.isReuseAddress());
            connectionlessClientBootstrap.setOption("child.connectTimeoutMillis", configuration.getConnectTimeout());
            connectionlessClientBootstrap.setOption("child.broadcast", configuration.isBroadcast());
            connectionlessClientBootstrap.setOption("sendBufferSize", configuration.getSendBufferSize());
            connectionlessClientBootstrap.setOption("receiveBufferSize", configuration.getReceiveBufferSize());

            // set any additional netty options
            if (configuration.getOptions() != null) {
                for (Map.Entry<String, Object> entry : configuration.getOptions().entrySet()) {
                    connectionlessClientBootstrap.setOption(entry.getKey(), entry.getValue());
                }
            }

            // set the pipeline factory, which creates the pipeline for each newly created channels
            connectionlessClientBootstrap.setPipelineFactory(pipelineFactory);
            // bind and store channel so we can close it when stopping
            Channel channel = connectionlessClientBootstrap.bind(new InetSocketAddress(0));
           
            allChannels.add(channel);
            // if udp connectionless sending is true we don't do a connect.
            // we just send on the channel created with bind which means
            // really fire and forget. You wont get an PortUnreachableException
            // if no one is listen on the port
            if (!configuration.isUdpConnectionlessSending()) {
                answer = connectionlessClientBootstrap.connect(new InetSocketAddress(configuration.getHost(), configuration.getPort()));
            } else {
                answer = new SucceededChannelFuture(channel);
            }
           
            if (LOG.isDebugEnabled()) {
                LOG.debug("Created new UDP client bootstrap connecting to {}:{} with options: {}",
                       new Object[]{configuration.getHost(), configuration.getPort(), connectionlessClientBootstrap.getOptions()});
            }
            return answer;
        }
    }
View Full Code Here

Examples of org.jboss.netty.bootstrap.ConnectionlessBootstrap

    private static final int SEND_COUNT = 20;
    private int receivedCount;
    private ConnectionlessBootstrap bootstrap;

    public void createNettyUdpReceiver() {
        bootstrap = new ConnectionlessBootstrap(new NioDatagramChannelFactory());
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline channelPipeline = Channels.pipeline();
                channelPipeline.addLast("StringDecoder", new StringDecoder(CharsetUtil.UTF_8));
View Full Code Here

Examples of org.jboss.netty.bootstrap.ConnectionlessBootstrap

    private static final int SEND_COUNT = 20;
    private int receivedCount;
    private ConnectionlessBootstrap bootstrap;

    public void createNettyUdpReceiver() {
        bootstrap = new ConnectionlessBootstrap(new NioDatagramChannelFactory());
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline channelPipeline = Channels.pipeline();
                channelPipeline.addLast("StringDecoder", new StringDecoder(CharsetUtil.UTF_8));
View Full Code Here

Examples of org.jboss.netty.bootstrap.ConnectionlessBootstrap

  {
    this.iam = iam;
    this.serverAddress = new InetSocketAddress(remoteHost,remotePort);
    DatagramChannelFactory f = new NioDatagramChannelFactory(executorService);
    // Create only one bootstrap per instance. But use it to make multiple udp channels.
    b = new ConnectionlessBootstrap(f);
    ChannelPipeline p = b.getPipeline();
    p.addLast("eventDecoder",EVENT_DECODER);
    p.addLast("businessHandler", businessHandler);
    b.setOption("broadcast", "true");
  }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.