List of usage examples for io.netty.channel ChannelInitializer ChannelInitializer
ChannelInitializer
From source file:books.netty.protocol.websocket.server.WebSocketServer.java
License:Apache License
public void run(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/* w w w . j a v a 2 s. c o m*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("http-codec", new HttpServerCodec()); pipeline.addLast("aggregator", new HttpObjectAggregator(65536)); ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler()); pipeline.addLast("handler", new WebSocketServerHandler()); } }); Channel ch = b.bind(port).sync().channel(); System.out.println("Web socket server started at port " + port + '.'); System.out.println("Open your browser and navigate to http://localhost:" + port + '/'); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:bridgempp.bot.wrapper.BotWrapper.java
/** * @param args/*from ww w . jav a 2s . c o m*/ * the command line arguments */ public static void main(String[] args) { EventLoopGroup loopGroup = new NioEventLoopGroup(2); bootstrap = new Bootstrap(); bootstrap.group(loopGroup); bootstrap.channel(NioSocketChannel.class); bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel channel) throws Exception { } }); File botsDir = new File("bots/"); if (!botsDir.exists()) { botsDir.mkdir(); Properties exampleBotProperties = new Properties(); try { writeDefaultConfig(exampleBotProperties); exampleBotProperties.store(new FileOutputStream("bots/exampleBot.config"), "Bot Wrapper Configuration"); } catch (IOException e) { e.printStackTrace(); } System.out.println("Created Example Config. Please Edit"); return; } for (File botConfig : botsDir.listFiles()) { botInitialize(botConfig); } }
From source file:c5db.control.ControlService.java
License:Apache License
private void startHttpRpc() { try {/*from w w w . j a va 2s .co m*/ ServerBootstrap serverBootstrap = new ServerBootstrap(); ServerBootstrap serverBootstrap1 = serverBootstrap.group(acceptConnectionGroup, ioWorkerGroup) .channel(NioServerSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.SO_BACKLOG, 100).childOption(ChannelOption.TCP_NODELAY, true) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // pipeline.addLast("logger", new LoggingHandler(LogLevel.DEBUG)); pipeline.addLast("http-server", new HttpServerCodec()); pipeline.addLast("aggregator", new HttpObjectAggregator(C5ServerConstants.MAX_CALL_SIZE)); pipeline.addLast("encode", new ServerHttpProtostuffEncoder()); pipeline.addLast("decode", new ServerHttpProtostuffDecoder()); pipeline.addLast("translate", new ServerDecodeCommandRequest()); pipeline.addLast("inc-messages", new MessageHandler()); } }); serverBootstrap.bind(modulePort).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // yay listenChannel = future.channel(); notifyStarted(); } else { LOG.error("Unable to bind to port {}", modulePort); notifyFailed(future.cause()); } } }); } catch (Exception e) { notifyFailed(e); } }
From source file:c5db.control.SimpleControlClient.java
License:Apache License
private void createClient() { client.group(ioWorkerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() { @Override// w w w. j a v a2s. c o m protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // pipeline.addLast("logger", new LoggingHandler(LogLevel.WARN)); pipeline.addLast("http-client", new HttpClientCodec()); pipeline.addLast("aggregator", new HttpObjectAggregator(C5ServerConstants.MAX_CALL_SIZE)); pipeline.addLast("encode", new ClientHttpProtostuffEncoder()); pipeline.addLast("decode", new ClientHttpProtostuffDecoder()); pipeline.addLast("translate", new ClientEncodeCommandRequest()); } }); }
From source file:c5db.discovery.BeaconService.java
License:Apache License
@Override protected void doStart() { eventLoopGroup.next().execute(() -> { bootstrap = new Bootstrap(); bootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, true) .handler(new ChannelInitializer<DatagramChannel>() { @Override/*w ww .j ava2 s. c o m*/ protected void initChannel(DatagramChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("protobufDecoder", new UdpProtostuffDecoder<>(Availability.getSchema(), false)); p.addLast("protobufEncoder", new UdpProtostuffEncoder<>(Availability.getSchema(), false)); p.addLast("beaconMessageHandler", new BeaconMessageHandler()); } }); // Wait, this is why we are in a new executor... //noinspection RedundantCast bootstrap.bind(discoveryPort).addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { broadcastChannel = future.channel(); } else { LOG.error("Unable to bind! ", future.cause()); notifyFailed(future.cause()); } }); try { localIPs = getLocalIPs(); } catch (SocketException e) { LOG.error("SocketException:", e); notifyFailed(e); return; } fiber = fiberSupplier.getNewFiber(this::notifyFailed); fiber.start(); // Schedule fiber tasks and subscriptions. incomingMessages.subscribe(fiber, this::processWireMessage); nodeInfoRequests.subscribe(fiber, this::handleNodeInfoRequest); moduleInformationProvider.moduleChangeChannel().subscribe(fiber, this::updateCurrentModulePorts); if (localIPs.isEmpty()) { LOG.warn( "Found no IP addresses to broadcast to other nodes; as a result, only sending to loopback"); } fiber.scheduleAtFixedRate(this::sendBeacon, BEACON_SERVICE_INITIAL_BROADCAST_DELAY_MILLISECONDS, BEACON_SERVICE_BROADCAST_PERIOD_MILLISECONDS, TimeUnit.MILLISECONDS); C5Futures.addCallback(moduleInformationProvider.getOnlineModules(), (ImmutableMap<ModuleType, Integer> onlineModuleToPortMap) -> { updateCurrentModulePorts(onlineModuleToPortMap); notifyStarted(); }, this::notifyFailed, fiber); }); }
From source file:c5db.eventLogging.EventLogListener.java
License:Apache License
@Override protected void doStart() { nioEventLoopGroup.next().execute(() -> { Bootstrap bootstrap = new Bootstrap(); try {/* w w w. jav a2 s .co m*/ bootstrap.group(nioEventLoopGroup).channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, true) .handler(new ChannelInitializer<DatagramChannel>() { @Override protected void initChannel(DatagramChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("protostuffDecoder", new UdpProtostuffDecoder<>(EventLogEntry.getSchema(), false)); p.addLast("logger", new MsgHandler()); } }); bootstrap.bind(port).addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture future) throws Exception { channel = future.channel(); } }); notifyStarted(); } catch (Throwable t) { notifyFailed(t); } }); }
From source file:c5db.eventLogging.EventLogService.java
License:Apache License
@Override protected void doStart() { nioEventLoopGroup.next().execute(() -> { Bootstrap bootstrap = new Bootstrap(); try {/* ww w.ja v a 2s.c o m*/ bootstrap.group(nioEventLoopGroup).channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, true) .handler(new ChannelInitializer<DatagramChannel>() { @Override protected void initChannel(DatagramChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("protostuffEncoder", new UdpProtostuffEncoder<>(EventLogEntry.getSchema(), false)); } }); bootstrap.bind(port).addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture future) throws Exception { broadcastChannel = future.channel(); } }); eventLogChannel.subscribe(fiber, msg -> { if (broadcastChannel == null) { LOG.debug("Broadcast channel isn't read yet, dropped message"); return; } LOG.trace("Sending event {}", msg); broadcastChannel .writeAndFlush(new UdpProtostuffEncoder.UdpProtostuffMessage<>(sendAddress, msg)); }); fiber.start(); notifyStarted(); } catch (Throwable t) { fiber.dispose(); notifyFailed(t); } }); }
From source file:c5db.regionserver.RegionServerService.java
License:Apache License
@Override protected void doStart() { fiber.start();//from w w w .j a v a2 s . c om fiber.execute(() -> { // we need the tablet module: ListenableFuture<C5Module> f = server.getModule(ModuleType.Tablet); Futures.addCallback(f, new FutureCallback<C5Module>() { @Override public void onSuccess(final C5Module result) { tabletModule = (TabletModule) result; bootstrap.group(acceptGroup, workerGroup).option(ChannelOption.SO_REUSEADDR, true) .childOption(ChannelOption.TCP_NODELAY, true).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("http-server-codec", new HttpServerCodec()); p.addLast("http-agg", new HttpObjectAggregator(C5ServerConstants.MAX_CALL_SIZE)); p.addLast("websocket-agg", new WebSocketFrameAggregator(C5ServerConstants.MAX_CALL_SIZE)); p.addLast("decoder", new WebsocketProtostuffDecoder("/websocket")); p.addLast("encoder", new WebsocketProtostuffEncoder()); p.addLast("handler", new RegionServerHandler(RegionServerService.this)); } }); bootstrap.bind(port).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { listenChannel = future.channel(); notifyStarted(); } else { LOG.error("Unable to find Region Server to {} {}", port, future.cause()); notifyFailed(future.cause()); } } }); } @Override public void onFailure(Throwable t) { notifyFailed(t); } }, fiber); }); }
From source file:c5db.replication.ReplicatorService.java
License:Apache License
/** * ********** Service startup/registration and shutdown/termination ************** */// w ww .j av a 2 s .com @Override protected void doStart() { // must start the fiber up early. fiber = fiberSupplier.getNewFiber(this::failModule); setupEventChannelSubscription(); fiber.start(); C5Futures.addCallback(getDependedOnModules(), (ignore) -> { ChannelInitializer<SocketChannel> initer = new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("frameDecode", new ProtobufVarint32FrameDecoder()); p.addLast("pbufDecode", new ProtostuffDecoder<>(ReplicationWireMessage.getSchema())); p.addLast("frameEncode", new ProtobufVarint32LengthFieldPrepender()); p.addLast("pbufEncoder", new ProtostuffEncoder<ReplicationWireMessage>()); p.addLast(new MessageHandler()); } }; serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.SO_BACKLOG, 100) .childOption(ChannelOption.TCP_NODELAY, true).childHandler(initer); //noinspection RedundantCast serverBootstrap.bind(port).addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { LOG.info("successfully bound node {} port {} ", nodeId, port); listenChannel = future.channel(); } else { LOG.error("Unable to bind! ", future.cause()); failModule(future.cause()); } }); outgoingBootstrap.group(workerGroup).channel(NioSocketChannel.class) .option(ChannelOption.SO_REUSEADDR, true).option(ChannelOption.TCP_NODELAY, true) .handler(initer); //noinspection Convert2MethodRef outgoingRequests.subscribe(fiber, message -> handleOutgoingMessage(message), // Clean up cancelled requests. message -> handleCancelledSession(message.getSession())); notifyStarted(); }, (Throwable t) -> { LOG.error("ReplicatorService unable to retrieve modules!", t); failModule(t); }, fiber); }
From source file:ca.lambtoncollege.netty.webSocket.ClientWebSocket.java
public static void main(String[] args) throws Exception { URI uri = new URI(URL); String scheme = uri.getScheme() == null ? "http" : uri.getScheme(); final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); final int port; if (uri.getPort() == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80;/* ww w. ja va 2 s. co m*/ } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } else { port = -1; } } else { port = uri.getPort(); } if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) { System.err.println("Only WS(S) is supported."); return; } final boolean ssl = "wss".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } else { sslCtx = null; } EventLoopGroup group = new NioEventLoopGroup(); try { // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. final ClientHandlerWebSocket handler = new ClientHandlerWebSocket(WebSocketClientHandshakerFactory .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), host, port)); } p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler); } }); Channel ch = b.connect(uri.getHost(), port).sync().channel(); handler.handshakeFuture().sync(); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); while (true) { String msg = console.readLine(); if (msg == null) { break; } else if ("bye".equals(msg.toLowerCase())) { ch.writeAndFlush(new CloseWebSocketFrame()); ch.closeFuture().sync(); break; } else if ("ping".equals(msg.toLowerCase())) { WebSocketFrame frame = new PingWebSocketFrame( Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 })); ch.writeAndFlush(frame); } else { WebSocketFrame frame = new TextWebSocketFrame(msg); ch.writeAndFlush(frame); } } } finally { group.shutdownGracefully(); } }