Example usage for io.netty.channel.socket SocketChannel closeFuture

List of usage examples for io.netty.channel.socket SocketChannel closeFuture

Introduction

In this page you can find the example usage for io.netty.channel.socket SocketChannel closeFuture.

Prototype

ChannelFuture closeFuture();

Source Link

Document

Returns the ChannelFuture which will be notified when this channel is closed.

Usage

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 ww  .  j  ava2s.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: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;/*from  www  .j a  va 2 s .  c o 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();
    }
}

From source file:chapter10.WebSocketServer.java

License:Apache License

public void run(int port) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {/* w  w w .ja v  a  2s  .c  o m*/
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        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:cn.npt.net.websocket.WebSocketClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
    final String host = uri.getHost() == null ? "192.168.20.71" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;// ww w . jav a  2  s  .  co m
        } else if ("wss".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 = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } 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 BaseWebSocketClientHandler handler = new EchoWebSocketClientHandler(
                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();
    }
}

From source file:com.addthis.hydra.query.web.QueryServerInitializer.java

License:Apache License

@Override
protected void initChannel(final SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    if (log.isTraceEnabled()) {
        log.trace("New socket connection {}", ch);
        ch.closeFuture().addListener(new ChannelFutureListener() {
            @Override/*from w  w w.  jav a  2 s.  co m*/
            public void operationComplete(ChannelFuture future) throws Exception {
                log.trace("channel closed {}", ch);
            }
        });
    }
    pipeline.addLast("decoder", new HttpRequestDecoder(maxInitialLineLength, maxHeaderSize, maxChunkSize));
    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("aggregator", new HttpObjectAggregator(maxContentLength));
    // compression is neat, but a little buggy
    //        pipeline.addLast(ImmediateEventExecutor.INSTANCE, "compressor", new HttpContentCompressor());
    pipeline.addLast("query", httpQueryHandler);

}

From source file:com.aerofs.baseline.http.AcceptedChannelInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel channel) throws Exception {
    LOGGER.trace("{}: setup", Channels.getHexText(channel));

    // time how long channels live
    channel.closeFuture().addListener(new GenericFutureListener<Future<Void>>() {

        private final Timer.Context lifetimeContext = CHANNEL_LIFETIME_TIMER.time();

        @Override/*  www. java 2s  .c om*/
        public void operationComplete(Future<Void> future) throws Exception {
            lifetimeContext.stop();
        }
    });

    // create the channel pipeline
    channel.pipeline().addLast(new IdleTimeoutHandler(0, 0, (int) http.getIdleTimeout(), TimeUnit.MILLISECONDS),
            new HttpServerCodec(HTTP_MAX_INITIAL_LINE_LENGTH, HTTP_MAX_HEADER_SIZE, HTTP_MAX_CHUNK_SIZE, false),
            requestHeaderAssigner, new BufferingHttpObjectHandler(),
            new HttpRequestHandler(applicationHandler, baseUri, applicationExecutor, timer),
            finalInboundHandler);
}

From source file:com.ahanda.techops.noty.clientTest.Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    if (args.length == 1) {
        System.setProperty("PINT.conf", args[0]);
    }//from  w ww. j a v  a  2 s  .c  om

    if (System.getProperty("PINT.conf") == null)
        throw new IllegalArgumentException();

    JsonNode config = null;
    Config cf = Config.getInstance();
    cf.setupConfig();

    String scheme = "http";
    String host = cf.getHttpHost();
    int port = cf.getHttpPort();

    if (port == -1) {
        port = 8080;
    }

    if (!"http".equalsIgnoreCase(scheme)) {
        l.warn("Only HTTP is supported.");
        return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new HttpClientCodec());
                // p.addLast( "decoder", new HttpResponseDecoder());
                // p.addLast( "encoder", new HttpRequestEncoder());

                // Remove the following line if you don't want automatic content decompression.
                // p.addLast(new HttpContentDecompressor());

                // Uncomment the following line if you don't want to handle HttpContents.
                p.addLast(new HttpObjectAggregator(10485760));

                p.addLast(new ClientHandler());
            }
        });

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        ClientHandler client = new ClientHandler();
        client.login(ch, ClientHandler.credential);
        // ClientHandler.pubEvent( ch, ClientHandler.event );

        // Wait for the server to close the connection.
        ch.closeFuture().sync();
        l.info("Closing Client side Connection !!!");
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}

From source file:com.allanbank.mongodb.netty.NettyChannelInit.java

License:Apache License

/**
 * {@inheritDoc}/*from   ww w  .  j  av a 2 s . c o m*/
 * <p>
 * Overridden to initialize the channel's processing pipeline.
 * </p>
 */
@Override
public void initChannel(final SocketChannel ch) throws Exception {

    final ChannelPipeline pipeline = ch.pipeline();

    // Make sure we know when the connection gets closed.
    ch.closeFuture().addListener(new NettyCloseListener(myResponseListener));

    SSLEngine engine = null;
    final SocketFactory socketFactory = myClientConfig.getSocketFactory();
    if (socketFactory instanceof SslEngineFactory) {

        final SslEngineFactory factory = (SslEngineFactory) socketFactory;
        engine = factory.createSSLEngine();

    } else if (socketFactory instanceof SSLSocketFactory) {
        engine = createVanillaEngine((SSLSocketFactory) socketFactory);
    }

    if (engine != null) {
        engine.setUseClientMode(true);

        final SslHandler handler = new SslHandler(engine, false /* startTLS */);
        pipeline.addLast("ssl", handler);

        if (socketFactory instanceof SocketConnectionListener) {
            handler.handshakeFuture().addListener(new NettyTlsConnectionCompletedListener(
                    (SocketConnectionListener) socketFactory, engine, ch));
        }
    }

    // Read side.
    pipeline.addLast("readTimeoutHandler",
            new ReadTimeoutHandler(myClientConfig.getReadTimeout(), TimeUnit.MILLISECONDS));
    pipeline.addLast("bufToMessageHandler", new ByteToMessageDecoder(myDecoderCache));
    pipeline.addLast("replyHandler", new NettyReplyHandler(myResponseListener));
}

From source file:com.cmz.http.websocketx.client.WebSocketClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "ws" : uri.getScheme();
    final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("ws".equalsIgnoreCase(scheme)) {
            port = 80;// w w w. j ava2s  .  c om
        } else if ("wss".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 = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } 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 WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
                .newHandshaker(uri, WebSocketVersion.V13, null, true, 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),
                        WebSocketClientCompressionHandler.INSTANCE, 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();
    }
}

From source file:com.digitalpetri.modbus.slave.ModbusTcpSlave.java

License:Apache License

public CompletableFuture<ModbusTcpSlave> bind(String host, int port) {
    CompletableFuture<ModbusTcpSlave> bindFuture = new CompletableFuture<>();

    ServerBootstrap bootstrap = new ServerBootstrap();

    ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
        @Override/*from   w  w w  .ja  va2s  .c om*/
        protected void initChannel(SocketChannel channel) throws Exception {
            channelCounter.inc();
            logger.info("channel initialized: {}", channel);

            channel.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
            channel.pipeline()
                    .addLast(new ModbusTcpCodec(new ModbusResponseEncoder(), new ModbusRequestDecoder()));
            channel.pipeline().addLast(new ModbusTcpSlaveHandler(ModbusTcpSlave.this));

            channel.closeFuture().addListener(future -> channelCounter.dec());
        }
    };

    config.getBootstrapConsumer().accept(bootstrap);

    bootstrap.group(config.getEventLoop()).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(initializer)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    bootstrap.bind(host, port).addListener((ChannelFuture future) -> {
        if (future.isSuccess()) {
            Channel channel = future.channel();
            serverChannels.put(channel.localAddress(), channel);
            bindFuture.complete(ModbusTcpSlave.this);
        } else {
            bindFuture.completeExceptionally(future.cause());
        }
    });

    return bindFuture;
}