Search in sources :

Example 11 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project netty by netty.

the class WebSocketClient method main.

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;
        } 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();
    }
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) InputStreamReader(java.io.InputStreamReader) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame) URI(java.net.URI) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) BufferedReader(java.io.BufferedReader) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) Bootstrap(io.netty.bootstrap.Bootstrap) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Example 12 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project netty by netty.

the class Http2Server method start.

public ChannelFuture start() throws Exception {
    final SslContext sslCtx = configureTLS();
    ServerBootstrap b = new ServerBootstrap();
    b.option(ChannelOption.SO_BACKLOG, 1024);
    b.group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()), new Http2OrHttpHandler());
        }
    });
    Channel ch = b.bind(PORT).sync().channel();
    return ch.closeFuture();
}
Also used : NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) SocketChannel(io.netty.channel.socket.SocketChannel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) CertificateException(java.security.cert.CertificateException) SSLException(javax.net.ssl.SSLException) SslContext(io.netty.handler.ssl.SslContext)

Example 13 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project netty by netty.

the class FileServer method main.

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc()));
                }
                p.addLast(new StringEncoder(CharsetUtil.UTF_8), new LineBasedFrameDecoder(8192), new StringDecoder(CharsetUtil.UTF_8), new ChunkedWriteHandler(), new FileServerHandler());
            }
        });
        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();
        // Wait until the server socket is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down all event loops to terminate all threads.
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LineBasedFrameDecoder(io.netty.handler.codec.LineBasedFrameDecoder) StringDecoder(io.netty.handler.codec.string.StringDecoder) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) StringEncoder(io.netty.handler.codec.string.StringEncoder) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext)

Example 14 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project netty by netty.

the class DiscardClient method main.

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }
    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();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                }
                p.addLast(new DiscardClientHandler());
            }
        });
        // Make the connection attempt.
        ChannelFuture f = b.connect(HOST, PORT).sync();
        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelPipeline(io.netty.channel.ChannelPipeline) SslContext(io.netty.handler.ssl.SslContext)

Example 15 with SocketChannel

use of io.netty.channel.socket.SocketChannel in project netty by netty.

the class DiscardServer method main.

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc()));
                }
                p.addLast(new DiscardServerHandler());
            }
        });
        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(PORT).sync();
        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) SslContext(io.netty.handler.ssl.SslContext)

Aggregations

SocketChannel (io.netty.channel.socket.SocketChannel)65 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)34 ChannelPipeline (io.netty.channel.ChannelPipeline)31 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)28 Bootstrap (io.netty.bootstrap.Bootstrap)27 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)26 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)24 ChannelFuture (io.netty.channel.ChannelFuture)22 EventLoopGroup (io.netty.channel.EventLoopGroup)21 Channel (io.netty.channel.Channel)17 SslContext (io.netty.handler.ssl.SslContext)15 IOException (java.io.IOException)14 InetSocketAddress (java.net.InetSocketAddress)14 LengthFieldBasedFrameDecoder (io.netty.handler.codec.LengthFieldBasedFrameDecoder)9 LoggingHandler (io.netty.handler.logging.LoggingHandler)8 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)7 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)7 ByteBuf (io.netty.buffer.ByteBuf)6 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)6 ChannelInitializer (io.netty.channel.ChannelInitializer)6