Netty应用示例(一)Socket应用示例

1、示例说明

本示例为基于行字符串的回显应用示例,客户端通过标准输入获取行字符串,并将字符串发送到服务端;服务端读取客户端行数据,解码之后将数据回写给客户端,同事服务端实现与客户端的读写心跳检测等;

2、服务端说明

服务端基于netty创建,解码器为LineBasedFrameDecoder和StringDecoder,主要功能是将ByteBuf类型数据解码转换为String类型数据;心跳机制基于IdleStateHandler实现;

2.1、服务端代码示例

SocketEchoServer 源码:

public class SocketEchoServer {
    private static  int PORT = 9999;


    public static void main(String[] args){
        SocketEchoServer.startServer(PORT);
    }





    private static void startServer(int port){
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 256)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast("lineDecodeHandler", new LineBasedFrameDecoder(1024, false, false))
                                    .addLast("stringDecoder", new StringDecoder())
                                    .addLast("heartBeatHandler", new IdleStateHandler(0,0, 30))
                                    .addLast("echoHandler", new SocketEchoServerHandler());
                        }
                    });
            ChannelFuture cf = sb.bind(PORT).sync();
            System.out.println("---- server bind success on port:" + PORT + " ----");
            cf.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}

说明:

  • 创建服务端Channel的事件处理线程组bossGroup,本处设置线程个数为1个;
  • 创建客户端连接Channel的事件处理线程组workerGroup,线程个数为默认(处理器个数的2倍);
  • 创建ServerBootstrap并设置相关参数,设置服务端Channel为NioServerSocketChannel,设置服务端的连接缓存为256,添加子连接的ChannelHandler为LineBasedFrameDecoder、StringDecoder、IdleStateHandler、SocketEchoServerHandler;
  • 绑定本地端口9999,并同步等待绑定结果;
  • 同步等待服务端监听连接的关闭结果;

2.2、SocketEchoServerHandler示例

SocketEchoServerHandler源码:

public class SocketEchoServerHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress address = (InetSocketAddress)ctx.channel().remoteAddress();
        System.out.println("---- client active: host=" + address.getHostName() + ",port=" + address.getPort() + "----");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress address = (InetSocketAddress)ctx.channel().remoteAddress();
        System.out.println("---- client inactive: host=" + address.getHostName() + ",port=" + address.getPort() + "----");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof String){
            String str = (String)msg;
            ctx.writeAndFlush(Unpooled.copiedBuffer(str.getBytes()));
            System.out.println("recv form client:" + str);
            return;
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent) evt;
            DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
            String dt = DateTime.now().toString(format);
            switch (event.state()){
                case ALL_IDLE:
                    System.out.println(dt + ":服务端与客户端读写超时!");
                    break;
                case READER_IDLE:
                    System.out.println(dt + ":服务端读超时!");
                    break;
                case WRITER_IDLE:
                    System.out.println(dt + ":服务端写超时!");
                    break;
            }
        }
    }
}

channelRead:读取解码器解码转换后的String对象,将对象回写到对应的客户端;

userEventTriggered:若事件类型为IdleStateEvent表明为心跳检测事件,获取对应事件类型并打印;

3、客户端说明

客户端主要功能为连接服务器,从标准输入中读取行字符串,将行数据发送给服务端,同时接收服务端回写的数据;

3.1、客户端示例

SocketEchoClient源码:

public class SocketEchoClient {
    private static String LOCAL_HOST = "127.0.0.1";
    private static int SERVER_PORT = 9999;

    public static void main(String[] args){
        SocketEchoClient.startClient(SERVER_PORT);
    }

    private static void startClient(int serverPort){
        NioEventLoopGroup group = new NioEventLoopGroup(1);

        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                            nioSocketChannel.pipeline().addLast("lineDecodeHandler", new LineBasedFrameDecoder(1024, false, false))
                                    .addLast("stringDecoder",new StringDecoder())
                                    .addLast("echoClientHandler", new SocketEchoClientHandler());
                        }
                    });
            ChannelFuture cf = b.connect(LOCAL_HOST, SERVER_PORT).sync();
            System.out.println("client connect to server success! host:" + LOCAL_HOST + ":" + SERVER_PORT);
            cf.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }
    
}

说明:

  • 创建一个线程的EventLoopGroup;
  • 设置客户端Channel类型为NioSocketChannel;
  • 设置客户端ChannelHandler的为LineBasedFrameDecoder、StringDecoder及SocketEchoClientHandler;
  • 同步连接服务器;

3.2、SocketEchoClientHandler示例

SocketEchoClientHandler源码:

public class SocketEchoClientHandler extends ChannelInboundHandlerAdapter{
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof String){
            String str = (String)msg;
            System.out.println("recv form server:" + str);
            return;
        }
    }


    @Override
    public void channelActive(final ChannelHandlerContext ctx) throws Exception {
        try {
            new Thread(new Runnable() {
                public void run() {
                    Scanner scanner = new Scanner(System.in);
                    while (scanner.hasNextLine()){
                        String line = scanner.nextLine();
                        if(line.startsWith("##stop")){
                            ctx.close();
                            break;
                        }
                        line += System.getProperty("line.separator");
                        System.out.println(line);
                        ctx.writeAndFlush(Unpooled.copiedBuffer(line.getBytes()));
                    }
                }
            }).start();
        }catch (Exception e){
            e.printStackTrace();
            ctx.close();
        }
    }
}

channelRead:读取服务端回写数据;

channelActive:客户端连接成功后,创建并启动读取标准输入处理的线程,线程中读取行数据并将数据发送给服务端;

4、应用演示示例

以下为服务端及客户端的实例输入输出,序号为时序。

服务端:

9795603-669f90581ad0c8b4.png
服务端.png

客户端:

9795603-e59a852bfdb63b36.png
客户端.png

应用示例源码:https://github.com/zhaozhou11/netty-demo.git

Netty源码愫读:
Netty源码愫读(一)ByteBuf相关源码学习 【https://www.jianshu.com/p/016daa404957
Netty源码愫读(二)Channel相关源码学习【https://www.jianshu.com/p/02eac974258e
Netty源码愫读(三)ChannelPipeline、ChannelHandlerContext相关源码学习【https://www.jianshu.com/p/be82d0fcdbcc
Netty源码愫读(四)ChannelHandler相关源码学习【https://www.jianshu.com/p/6ee0a3b9d73a
Netty源码愫读(五)EventLoop与EventLoopGroup相关源码学习【https://www.jianshu.com/p/05096995d296
Netty源码愫读(六)ServerBootstrap相关源码学习【https://www.jianshu.com/p/a71a9a0291f3

Netty应用实战:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Netty WebSocket 示例代码: ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.stream.ChunkedWriteHandler; import io.netty.util.concurrent.DefaultThreadFactory; public class WebSocketServer { private static final int PORT = 8080; public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("boss")); EventLoopGroup workerGroup = new NioEventLoopGroup(0, new DefaultThreadFactory("worker")); try { ServerBootstrap bootstrap = new ServerBootstrap() .group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new ChunkedWriteHandler()); pipeline.addLast(new WebSocketFrameAggregator(65536)); pipeline.addLast(new WebSocketServerProtocolHandler("/ws")); pipeline.addLast(new WebSocketServerHandler()); } }); Channel ch = bootstrap.bind(PORT).sync().channel(); System.out.println("WebSocket 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(); } } } ``` 上述代码创建了一个 Netty WebSocket 服务器,监听端口为 8080。新连接会通过 `ChannelInitializer` 进行处理,其中添加了以下几个处理器: - `HttpServerCodec`:用于将 HTTP 请求和响应编解码为 Netty 的 `HttpRequest` 和 `HttpResponse` 对象。 - `HttpObjectAggregator`:用于将 HTTP 消息的多个部分合并成一个完整的消息。 - `ChunkedWriteHandler`:用于处理大文件或者大数据流,将数据以块(Chunk)的形式写入到客户端。 - `WebSocketFrameAggregator`:用于将 WebSocket 帧的多个部分合并成一个完整的帧。 - `WebSocketServerProtocolHandler`:用于处理 WebSocket 握手和帧的编解码。 - `WebSocketServerHandler`:自定义的处理器,用于处理客户端的 WebSocket 帧。 `WebSocketServerHandler` 的示例代码如下: ```java import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator; public class WebSocketServerHandler extends SimpleChannelInboundHandler<WebSocketFrame> { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("Client connected: " + ctx.channel().remoteAddress()); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("Client disconnected: " + ctx.channel().remoteAddress()); } @Override protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception { if (frame instanceof TextWebSocketFrame) { String text = ((TextWebSocketFrame) frame).text(); System.out.println("Received message: " + text); ctx.channel().writeAndFlush(new TextWebSocketFrame("Server received: " + text)); } else { throw new UnsupportedOperationException("Unsupported frame type: " + frame.getClass().getName()); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.err.println("Exception caught: " + cause.getMessage()); ctx.close(); } } ``` 上述代码实现了 `SimpleChannelInboundHandler` 接口,用于处理客户端发送的 WebSocket 帧。当收到 `TextWebSocketFrame` 类型的帧时,会将其内容打印到控制台,并将其转发给客户端。其他类型的帧会抛出异常。 客户端可以通过 JavaScript 代码连接到服务器: ```javascript let socket = new WebSocket("ws://localhost:8080/ws"); socket.onopen = function() { console.log("Connected to WebSocket server."); socket.send("Hello, WebSocket server!"); }; socket.onmessage = function(event) { console.log("Received message: " + event.data); }; socket.onclose = function(event) { console.log("Disconnected from WebSocket server."); }; ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值