public Channel bind() { return bootstrap.bind().syncUninterruptibly().channel(); }
@Override public ChannelFuture bind(InetSocketAddress address) { return this.bootstrap.bind(address).addListener(future -> { if (future.isSuccess()) { onBindSuccess(address); } else { onBindFailure(address, future.cause()); } }); }
/** * Recursivesly binds the given bootstrap to the given interfaces. * * @param bootstrap the bootstrap to bind * @param ifaces an iterator of interfaces to which to bind * @param port the port to which to bind * @param future the future to completed once the bootstrap has been bound to all provided interfaces */ private void bind(Bootstrap bootstrap, Iterator<String> ifaces, int port, CompletableFuture<Void> future) { if (ifaces.hasNext()) { String iface = ifaces.next(); bootstrap.bind(iface, port).addListener((ChannelFutureListener) f -> { if (f.isSuccess()) { log.info("UDP server listening for connections on {}:{}", iface, port); channel = (DatagramChannel) f.channel(); bind(bootstrap, ifaces, port, future); } else { log.warn("Failed to bind TCP server to port {}:{} due to {}", iface, port, f.cause()); future.completeExceptionally(f.cause()); } }); } else { future.complete(null); } }
private CompletableFuture<Void> bootstrapServer() { Bootstrap serverBootstrap = new Bootstrap() .group(group) .channelFactory(() -> new NioDatagramChannel(InternetProtocolFamily.IPv4)) .handler(new SimpleChannelInboundHandler<Object>() { @Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { // Nothing will be sent. } }) .option(ChannelOption.IP_MULTICAST_IF, iface) .option(ChannelOption.SO_REUSEADDR, true); CompletableFuture<Void> future = new CompletableFuture<>(); serverBootstrap.bind(localAddress).addListener((ChannelFutureListener) f -> { if (f.isSuccess()) { serverChannel = f.channel(); future.complete(null); } else { future.completeExceptionally(f.cause()); } }); return future; }
/** * Listing 8.8 Using Bootstrap with DatagramChannel */ public void bootstrap() { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(new OioEventLoopGroup()).channel( OioDatagramChannel.class).handler( new SimpleChannelInboundHandler<DatagramPacket>() { @Override public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception { // Do something with the packet } } ); ChannelFuture future = bootstrap.bind(new InetSocketAddress(0)); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { System.out.println("Channel bound"); } else { System.err.println("Bind attempt failed"); channelFuture.cause().printStackTrace(); } } }); } }
public void run() throws Exception { Channel ch = bootstrap.bind(0).sync().channel(); long pointer = 0; for (;;) { long len = file.length(); if (len < pointer) { // file was reset pointer = len; } else if (len > pointer) { // Content was added RandomAccessFile raf = new RandomAccessFile(file, "r"); raf.seek(pointer); String line; while ((line = raf.readLine()) != null) { ch.writeAndFlush(new LogEvent(null, -1, file.getAbsolutePath(), line)); } pointer = raf.getFilePointer(); raf.close(); } try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.interrupted(); break; } } }
clientBootstrap.bind().addListener((ChannelFutureListener) f -> { if (f.isSuccess()) { clientChannel = (DatagramChannel) f.channel();
private void createServer(Listener listener, EventLoopGroup eventLoopGroup, ChannelFactory<? extends DatagramChannel> channelFactory) { this.eventLoopGroup = eventLoopGroup; try { Bootstrap b = new Bootstrap(); b.group(eventLoopGroup)//默认是根据机器情况创建Channel,如果机器支持ipv6,则无法使用ipv4的地址加入组播 .channelFactory(channelFactory) .option(ChannelOption.SO_BROADCAST, true) .handler(getChannelHandler()); initOptions(b); //直接绑定端口,不要指定host,不然收不到组播消息 b.bind(port).addListener(future -> { if (future.isSuccess()) { logger.info("udp server start success on:{}", port); if (listener != null) listener.onSuccess(port); } else { logger.error("udp server start failure on:{}", port, future.cause()); if (listener != null) listener.onFailure(future.cause()); } }); } catch (Exception e) { logger.error("udp server start exception", e); if (listener != null) listener.onFailure(e); throw new ServiceException("udp server start exception, port=" + port, e); } }
channel = b.bind(address, port).sync().channel();
public Channel create(String bindAddr, int port) throws InterruptedException { NioEventLoopGroup group = new NioEventLoopGroup(1); Bootstrap b = new Bootstrap(); b.group(group) .channel(NioDatagramChannel.class) .handler(new ChannelInitializer<NioDatagramChannel>() { @Override public void initChannel(NioDatagramChannel ch) throws Exception { ch.pipeline().addLast(new PacketDecoder()); SimpleMessageHandler messageHandler = new SimpleMessageHandler(ch, nodeManager); nodeManager.setMessageSender(messageHandler); ch.pipeline().addLast(messageHandler); } }); return b.bind(bindAddr, port).sync().channel(); }
@Override public void launch(final MessageInput input) throws MisfireException { try { bootstrap = getBootstrap(input); final NettyTransportType transportType = nettyTransportConfiguration.getType(); int numChannels = (transportType == NettyTransportType.EPOLL || transportType == NettyTransportType.KQUEUE) ? workerThreads : 1; for (int i = 0; i < numChannels; i++) { LOG.debug("Starting channel on {}", socketAddress); bootstrap.bind(socketAddress) .addListener(new InputLaunchListener(channels, input, getRecvBufferSize())) .syncUninterruptibly(); } } catch (Exception e) { throw new MisfireException(e); } }
public void start(Class<? extends Channel> channel, InetSocketAddress address, EventLoopGroup eventLoop, ChannelFutureListener future) { new Bootstrap() .channel( channel ) .group( eventLoop ) .handler( new QueryHandler( bungee, listener ) ) .localAddress( address ) .bind().addListener( future ); } }
@Override public boolean startService() throws Exception{ boolean serviceFlag = super.startService(); Bootstrap b = new Bootstrap(); eventLoopGroup = new NioEventLoopGroup(); try { b.group(eventLoopGroup) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, false) // .option(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION,true) .option(ChannelOption.SO_REUSEADDR, true) //重用地址 .option(ChannelOption.SO_RCVBUF, 65536) .option(ChannelOption.SO_SNDBUF, 65536) .option(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(false)) // heap buf 's better .handler(new LoggingHandler(LogLevel.DEBUG)) .handler(channelInitializer); // .handler(new GameNetProtoMessageUdpServerChannelInitializer()); // 服务端监听在9999端口 serverChannelFuture = b.bind(serverPort).sync(); // serverChannelFuture.channel().closeFuture().sync(); serverChannelFuture.channel().closeFuture().addListener(ChannelFutureListener.CLOSE); }catch (Exception e){ logger.error(e.toString(), e); serviceFlag = false; } return serviceFlag; }
/** * setIncomingSyslogs() here is to pass the message list * to handler for and then return back to TSDRSyslogCollectorImpl * for being interted into TSDR database. * * @throws InterruptedException */ @Override public void startServer() throws InterruptedException { b.bind(port.get()).sync(); status.set(true); }
@SuppressWarnings("checkstyle:IllegalCatch") private void startXtr() { if (listenOnXtrPort) { try { xtrChannel = (NioDatagramChannel) xtrBootstrap.bind(bindingAddress, xtrPort).sync().channel(); LOG.debug("Binding LISP xTR UDP listening socket to {}:{}", bindingAddress, xtrPort); } catch (Exception e) { LOG.error("Failed to open xTR socket ", e); } } }
@Override public ChannelFuture bindChannel(String address, int port, ChannelHandler handler) { if (this.active.get()) { Bootstrap bootstrap = new Bootstrap().group(this.eventGroup).channel(NioDatagramChannel.class).handler(handler); return bootstrap.bind(address, port); } else { throw new IllegalStateException("Network manager is not active."); } }
@Override public ChannelFuture bindDatagramChannel(String address, int port, ChannelHandler handler) throws IllegalStateException { if (this.active.get()) { Bootstrap bootstrap = new Bootstrap().group(this.eventGroup).channel(NioDatagramChannel.class).handler(handler); return bootstrap.bind(address, port); } else { throw new IllegalStateException("Network manager is not active."); } }
@Override public ChannelFuture bindDatagramChannel(String address, int port, ChannelHandler handler) throws IllegalStateException { if (this.active.get()) { Bootstrap bootstrap = new Bootstrap().group(this.eventGroup).channel(NioDatagramChannel.class).handler(handler); return bootstrap.bind(address, port); } else { throw new IllegalStateException("Network manager is not active."); } }
private void startUDPServer() throws InterruptedException { this.group = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(group).channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler((ChannelHandler) new NettyKdcUdpServerHandler(kdcContext)); b.bind(udpAddress.getPort()).sync(); }
public void run(int port) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(new ChineseProverbServerHandler()); b.bind(port).sync().channel().closeFuture().await(); } finally { group.shutdownGracefully(); } }