美文网首页Netty从入门到精通
Netty动手写代码 -- echo server

Netty动手写代码 -- echo server

作者: yllyx | 来源:发表于2019-06-06 10:56 被阅读0次

    一、前言

      netty是什么?根据自己的理解,就是一句话:非阻塞、基于事件驱动的网络应用服务开发框架,可以用来开发高性能、高可靠的服务端和客户端网络程序。关于netty架构的介绍,可参考Netty框架入门的介绍,本文做为入门篇,通过实例代码介绍如何使用netty。


    首先配置开发环境,开发环境使用的是IDEA,新建个空的MAVEN项目,在pom.xml中添加依赖。

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>zkh360</groupId>
      <artifactId>zkh-netty</artifactId>
      <version>1.0-SNAPSHOT</version>
    
      <dependencies>
        <!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
        <dependency>
          <groupId>io.netty</groupId>
          <artifactId>netty-all</artifactId>
          <version>4.1.36.Final</version>
        </dependency>
      </dependencies>
    
    </project>
    

    echo server是回显服务,用户输入什么,服务器将输入信息返回给客户端。EchoServer代码如下:

    import io.netty.bootstrap.ServerBootstrap;
    
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelOption;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    
    /**
     * @Author:Mark
     * @Email: yunxiang.lon@gmail.com
     * @Description:
     * @Date: Created on 20:52 2019/6/5
     * @Modify by: 
     */
    public class EchoServer {
        private int port;
    
        public DiscardServer(int port) {
            this.port = port;
        }
    
        public void run() throws Exception {
            EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                ServerBootstrap b = new ServerBootstrap(); // (2)
                b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class) // (3)
                    .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new DiscardServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)          // (5)
                    .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)
    
                // Bind and start to accept incoming connections.
                ChannelFuture f = b.bind(port).sync(); // (7)
    
                // 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();
            }
        }
    
        public static void main(String[] args) throws Exception {
            int port = 8090;
            if (args.length > 0) {
                port = Integer.parseInt(args[0]);
            }
    
            new DiscardServer(port).run();
        }
    
    }
    
    

    服务器端消息处理代码如下

    import io.netty.buffer.ByteBuf;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.util.ReferenceCountUtil;
    
    /**
     * @Author:Mark
     * @Email: yunxiang.lon@gmail.com
     * @Description:
     * @Date: Created on 20:34 2019/6/5
     * @Modify by: 
     */
    public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg){
            ctx.write(msg); //(1)
            ctx.close(); //(2)
        }
    
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
            // Close the connection when an exception is raised.
            cause.printStackTrace();
            ctx.close();
        }
    
    }
    
    

    运行服务端程序,telnet 27.0.0.1 8090,输入,显示如下:


    telnet服务器并输入

    上面只是简单的入门,回显是输入一个字符回显一个

    相关文章

      网友评论

        本文标题:Netty动手写代码 -- echo server

        本文链接:https://www.haomeiwen.com/subject/mqqyxctx.html