Java源码示例:org.jboss.netty.bootstrap.ConnectionlessBootstrap

示例1
public void startup(int port) {
	
	ChannelFactory channelFactory = new NioDatagramChannelFactory(Executors.newCachedThreadPool());
	
	bootstrap = new ConnectionlessBootstrap( channelFactory );
	bootstrap.setOption("reuseAddress", false);
	bootstrap.setOption("child.reuseAddress", false);		
	bootstrap.setOption("readBufferSize", 1024 * 1024 * 15); //15M
	bootstrap.setOption("writeBufferSize", 1024 * 20);		
	bootstrap.setOption("receiveBufferSizePredictor", new FixedReceiveBufferSizePredictor(1024 * 3));
	bootstrap.setOption("receiveBufferSizePredictorFactory", new FixedReceiveBufferSizePredictorFactory(1024 * 3));
	bootstrap.setPipelineFactory( new ChannelPipelineFactory() {
		@Override
		public ChannelPipeline getPipeline() throws Exception {
			ChannelPipeline pipeline = Channels.pipeline();
			pipeline.addLast("handler", new UdpServerChannelHandler());
			return pipeline;
		}			
	});		
	datagramChannel = (DatagramChannel) bootstrap.bind( new InetSocketAddress( port ) );
}
 
示例2
public void run() {
  // Configure the client.
  DatagramChannelFactory f = new NioDatagramChannelFactory(
      Executors.newCachedThreadPool(), workerCount);

  server = new ConnectionlessBootstrap(f);
  server.setPipeline(Channels.pipeline(RpcUtil.STAGE_RPC_MESSAGE_PARSER,
      rpcProgram, RpcUtil.STAGE_RPC_UDP_RESPONSE));

  server.setOption("broadcast", "false");
  server.setOption("sendBufferSize", SEND_BUFFER_SIZE);
  server.setOption("receiveBufferSize", RECEIVE_BUFFER_SIZE);

  // Listen to the UDP port
  ch = server.bind(new InetSocketAddress(port));
  InetSocketAddress socketAddr = (InetSocketAddress) ch.getLocalAddress();
  boundPort = socketAddr.getPort();

  LOG.info("Started listening to UDP requests at port " + boundPort + " for "
      + rpcProgram + " with workerCount " + workerCount);
}
 
示例3
public void run() {
  // Configure the client.
  DatagramChannelFactory f = new NioDatagramChannelFactory(
      Executors.newCachedThreadPool(), workerCount);

  server = new ConnectionlessBootstrap(f);
  server.setPipeline(Channels.pipeline(RpcUtil.STAGE_RPC_MESSAGE_PARSER,
      rpcProgram, RpcUtil.STAGE_RPC_UDP_RESPONSE));

  server.setOption("broadcast", "false");
  server.setOption("sendBufferSize", SEND_BUFFER_SIZE);
  server.setOption("receiveBufferSize", RECEIVE_BUFFER_SIZE);

  // Listen to the UDP port
  ch = server.bind(new InetSocketAddress(port));
  InetSocketAddress socketAddr = (InetSocketAddress) ch.getLocalAddress();
  boundPort = socketAddr.getPort();

  LOG.info("Started listening to UDP requests at port " + boundPort + " for "
      + rpcProgram + " with workerCount " + workerCount);
}
 
示例4
private ConnectionlessBootstrap createUdpServer() {
        DatagramChannelFactory udpFactory = new NioDatagramChannelFactory(Executors.newCachedThreadPool(), 4);
        ChannelPipelineFactory pipelineFactory = new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("test", new SimpleChannelHandler() {
                    @Override
                    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
                        String name = Thread.currentThread().getName();
                        logger.debug("sleep:{}", name);
                        Thread.sleep(10000);
//                        if (!name.equals("New I/O worker #1")) {
                            logger.debug("messageReceived thread-{} message:", Thread.currentThread().getName());
//                        }
                    }
                });
                return pipeline;
            }
        };
        ConnectionlessBootstrap udpBootstrap = new ConnectionlessBootstrap(udpFactory);
        udpBootstrap.setPipelineFactory(pipelineFactory);
        return udpBootstrap;
    }
 
示例5
@Override
public void start() {
  // setup Netty server
  ConnectionlessBootstrap serverBootstrap = new ConnectionlessBootstrap
      (new OioDatagramChannelFactory(Executors.newCachedThreadPool()));
  final syslogHandler handler = new syslogHandler();
  handler.setFormater(formaterProp);
  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();
}
 
示例6
public UdpClient(final UdpClientChannelHandler channelHandler) {
	
	bootstrap = new ConnectionlessBootstrap(new NioDatagramChannelFactory());
	bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		@Override
		public ChannelPipeline getPipeline() throws Exception {
			ChannelPipeline pipeline = Channels.pipeline();
			pipeline.addLast("handler", channelHandler);
			return pipeline;
		}
	});
	
	bootstrap.setOption("localAddress", new InetSocketAddress(10002));
	channel = bootstrap.bind();
}
 
示例7
void start(final int idleTimeMilliSeconds, final SocketAddress tcpAddress,
    final SocketAddress udpAddress) {

  tcpServer = new ServerBootstrap(new NioServerSocketChannelFactory(
      Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
  tcpServer.setPipelineFactory(new ChannelPipelineFactory() {
    private final HashedWheelTimer timer = new HashedWheelTimer();
    private final IdleStateHandler idleStateHandler = new IdleStateHandler(
        timer, 0, 0, idleTimeMilliSeconds, TimeUnit.MILLISECONDS);

    @Override
    public ChannelPipeline getPipeline() throws Exception {
      return Channels.pipeline(RpcUtil.constructRpcFrameDecoder(),
          RpcUtil.STAGE_RPC_MESSAGE_PARSER, idleStateHandler, handler,
          RpcUtil.STAGE_RPC_TCP_RESPONSE);
    }
  });

  udpServer = new ConnectionlessBootstrap(new NioDatagramChannelFactory(
      Executors.newCachedThreadPool()));

  udpServer.setPipeline(Channels.pipeline(RpcUtil.STAGE_RPC_MESSAGE_PARSER,
      handler, RpcUtil.STAGE_RPC_UDP_RESPONSE));

  tcpChannel = tcpServer.bind(tcpAddress);
  udpChannel = udpServer.bind(udpAddress);
  allChannels.add(tcpChannel);
  allChannels.add(udpChannel);

  LOG.info("Portmap server started at tcp://" + tcpChannel.getLocalAddress()
      + ", udp://" + udpChannel.getLocalAddress());
}
 
示例8
void start(final int idleTimeMilliSeconds, final SocketAddress tcpAddress,
    final SocketAddress udpAddress) {

  tcpServer = new ServerBootstrap(new NioServerSocketChannelFactory(
      Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
  tcpServer.setPipelineFactory(new ChannelPipelineFactory() {
    private final HashedWheelTimer timer = new HashedWheelTimer();
    private final IdleStateHandler idleStateHandler = new IdleStateHandler(
        timer, 0, 0, idleTimeMilliSeconds, TimeUnit.MILLISECONDS);

    @Override
    public ChannelPipeline getPipeline() throws Exception {
      return Channels.pipeline(RpcUtil.constructRpcFrameDecoder(),
          RpcUtil.STAGE_RPC_MESSAGE_PARSER, idleStateHandler, handler,
          RpcUtil.STAGE_RPC_TCP_RESPONSE);
    }
  });

  udpServer = new ConnectionlessBootstrap(new NioDatagramChannelFactory(
      Executors.newCachedThreadPool()));

  udpServer.setPipeline(Channels.pipeline(RpcUtil.STAGE_RPC_MESSAGE_PARSER,
      handler, RpcUtil.STAGE_RPC_UDP_RESPONSE));

  tcpChannel = tcpServer.bind(tcpAddress);
  udpChannel = udpServer.bind(udpAddress);
  allChannels.add(tcpChannel);
  allChannels.add(udpChannel);

  LOG.info("Portmap server started at tcp://" + tcpChannel.getLocalAddress()
      + ", udp://" + udpChannel.getLocalAddress());
}
 
示例9
@Override
public void start() throws KairosDBException
{
	// Configure the server.
	m_serverBootstrap = new ServerBootstrap(
			new NioServerSocketChannelFactory(
					Executors.newCachedThreadPool(),
					Executors.newCachedThreadPool()));

	// Configure the pipeline factory.
	m_serverBootstrap.setPipelineFactory(this);
	m_serverBootstrap.setOption("child.tcpNoDelay", true);
	m_serverBootstrap.setOption("child.keepAlive", true);
	m_serverBootstrap.setOption("reuseAddress", true);

	// Bind and start to accept incoming connections.
	m_serverBootstrap.bind(new InetSocketAddress(m_address, m_port));


	m_udpBootstrap = new ConnectionlessBootstrap(
			new NioDatagramChannelFactory());

	m_udpBootstrap.setOption("receiveBufferSizePredictorFactory", new FixedReceiveBufferSizePredictorFactory(m_maxSize));

	m_udpBootstrap.setPipelineFactory(this);

	m_udpBootstrap.bind(new InetSocketAddress(m_port));
}
 
示例10
@Override
public void start() throws KairosDBException
{
	// Configure the server.
	m_serverBootstrap = new ServerBootstrap(
			new NioServerSocketChannelFactory(
					Executors.newCachedThreadPool(),
					Executors.newCachedThreadPool()));

	// Configure the pipeline factory.
	m_serverBootstrap.setPipelineFactory(this);
	m_serverBootstrap.setOption("child.tcpNoDelay", true);
	m_serverBootstrap.setOption("child.keepAlive", true);
	m_serverBootstrap.setOption("reuseAddress", true);

	// Bind and start to accept incoming connections.
	m_serverBootstrap.bind(new InetSocketAddress(m_address, m_port));


	m_udpBootstrap = new ConnectionlessBootstrap(
			new NioDatagramChannelFactory());

	m_udpBootstrap.setOption("receiveBufferSizePredictorFactory", new FixedReceiveBufferSizePredictorFactory(m_maxSize));

	m_udpBootstrap.setPipelineFactory(this);

	m_udpBootstrap.bind(new InetSocketAddress(m_port));

}
 
示例11
@Test
    public void server() throws IOException, InterruptedException {

        final ConnectionlessBootstrap udpServer = createUdpServer();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                udpServer.bind(new InetSocketAddress("127.0.0.1", PORT));
                try {
                    logger.debug("server-await");
                    latch.await();
                } catch (InterruptedException ignored) {
                }
                logger.debug("server-shutdown");
                udpServer.shutdown();
            }
        });
        thread.start();
        Thread.sleep(1000);
        logger.debug("start--------");
//        ExecutorService executorService = Executors.newFixedThreadPool(10);
//        for (int i =0; i< 10; i++) {
//            executorService.execute(new Runnable() {
//                @Override
//                public void run() {
//                    try {
                        start();
//                    } catch (IOException e) {
//                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
//                    }
//                }
//            });
//        }
//        executorService.awaitTermination(120, TimeUnit.SECONDS) ;


        latch.countDown();

    }
 
示例12
public void startup(int port) {

		this.dataBootstrap = new ConnectionlessBootstrap(factory);
		dataBootstrap.setOption("receiveBufferSizePredictor", new FixedReceiveBufferSizePredictor(2048));
		dataBootstrap.setOption("receiveBufferSizePredictorFactory", new FixedReceiveBufferSizePredictorFactory(2048));

		this.dataBootstrap.getPipeline().addLast("handler", new SimpleChannelUpstreamHandler() {
			@Override
			public void messageReceived(ChannelHandlerContext ctx, final MessageEvent e) throws Exception {

				ChannelBuffer buffer = (ChannelBuffer) e.getMessage();

				if (buffer.readableBytes() < 12) {
					throw new IllegalArgumentException("A RTP packet must be at least 12 octets long");
				}

				byte b = buffer.readByte();
				byte version = (byte) (b & 0xc0);
				boolean padding = (b & 0x20) > 0; // mask 0010 0000
				boolean extension = (b & 0x10) > 0; // mask 0001 0000
				int contributingSourcesCount = b & 0x0f; // mask 0000 1111

				// Marker, Payload Type
				b = buffer.readByte();
				boolean marker = (b & 0x80) > 0; // mask 0000 0001
				int payloadType = (b & 0x7f); // mask 0111 1111

				int sequenceNumber = buffer.readUnsignedShort();
				long timestamp = buffer.readUnsignedInt();
				long ssrc = buffer.readUnsignedInt();

				// Read CCRC's
				if (contributingSourcesCount > 0) {
					for (int i = 0; i < contributingSourcesCount; i++) {
						long contributingSource = buffer.readUnsignedInt();
					}
				}

				// Read extension headers & data
				if (extension) {
					short extensionHeaderData = buffer.readShort();
					byte[] extensionData = new byte[buffer.readUnsignedShort() * 4];
					buffer.readBytes(extensionData);
				}

				if (!padding) {
					// No padding used, assume remaining data is the packet
					byte[] remainingBytes = new byte[buffer.readableBytes()];
					buffer.readBytes(remainingBytes);

					// remainingBytes == data
				} else {
					// Padding bit was set, so last byte contains the number of
					// padding octets that should be discarded.
					short lastByte = buffer.getUnsignedByte(buffer.readerIndex() + buffer.readableBytes() - 1);
					byte[] dataBytes = new byte[buffer.readableBytes() - lastByte];
					buffer.readBytes(dataBytes);

					// dataBytes == data

					// Discard rest of buffer.
					buffer.skipBytes(buffer.readableBytes());
				}

				// 应答
				ChannelBuffer replyBuffer = ChannelBuffers.copiedBuffer(REPLY_BYTES);
				e.getChannel().write(replyBuffer, e.getRemoteAddress());

			}
		});
		this.dataChannel = (DatagramChannel) this.dataBootstrap.bind(new InetSocketAddress(port));

	}
 
示例13
/**
 * Creates an UDP socket and handler pipeline for RTP channels
 * 
 * @param local local end-point address
 * @param remote remote end-point address
 * @param channelType channel type. Determines which handlers are put into the pipeline
 * @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(rtpExecutorService));
	final ConnectionlessBootstrap bootstrap = new ConnectionlessBootstrap(new OioDatagramChannelFactory(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();

			final AirPlayServer airPlayServer = AirPlayServer.getIstance();
			
			pipeline.addLast("executionHandler", airPlayServer.getChannelExecutionHandler());
			pipeline.addLast("exceptionLogger", exceptionLoggingHandler);
			pipeline.addLast("decoder", decodeHandler);
			pipeline.addLast("encoder", 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", inputToAudioRouterDownstreamHandler);
				
				/* Must come *after* the router, otherwise incoming packets are logged twice */
				pipeline.addLast("packetLogger", packetLoggingHandler);
			}
			else {
				/* Must come *before* the router, otherwise outgoing packets are logged twice */
				pipeline.addLast("packetLogger", packetLoggingHandler);
				pipeline.addLast("audioToOutputRouter", audioToOutputRouterUpstreamHandler);
				pipeline.addLast("timing", timingHandler);
				pipeline.addLast("resendRequester", resendRequestHandler);
				
				if (decryptionHandler != null){
					pipeline.addLast("decrypt", decryptionHandler);
				}
				
				if (audioDecodeHandler != null){
					pipeline.addLast("audioDecode", audioDecodeHandler);
				}
				
				pipeline.addLast("enqueue", 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 */
		rtpChannels.add(channel);

		/* Connect to remote address if one was provided */
		if (remote != null){
			channel.connect(remote);
		}
		
		didThrow = false;
		return channel;
	}
	finally {
		if (didThrow && (channel != null)){
			channel.close();
		}
	}
}