Netty (1)-回声服务器

Netty基于java nio(非阻塞) 实现,主要用于服务端与客户端之间的socket通信,其高性能号称单机可支持百万连接。其应用场景非常广泛,如物联网、分布式、聊天程序、网络游戏等。在基于java语言的项目中,要开发socket通信,netty目前几乎处于不可替代的地位。本篇将用netty实现一个简单的回声通信。

pom.xml

	<dependency>
    		<groupId>io.netty</groupId>
    		<artifactId>netty-all</artifactId>
    		<version>4.1.44.Final</version>
	</dependency>

服务端

以下代码是官网的一个服务器启动示例,run方法里面是启动netty服务器的固定语法,具体什么意思先不讨论。只要知道其中有一个自定义类EchoServerHandler,需要自己实现,另外设置了服务端口8080。

public class EchoServer {
    private int port;
    
    public EchoServer(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 EchoServerHandler());
                 }
             })
             .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 = 8080;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        }

        new EchoServer(port).run();
    }
}

实现消息回声

我们只需关注这个自定义类,它继承了输入适配器,只需覆盖channelRead方法即可接收消息。

public class EchoServerHandler extends ChannelInboundHandlerAdapter{

    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ctx.writeAndFlush(msg);//将收到的消息原样返回, 即回声
    } 
  • ChannelHandlerContext ctx:可用于对当前连接进行各种操作,比如这里回复消息。
  • Object msg:就是客户端发过来的消息对象。

客户端

在现实中,客户端可能是一台自动售货机、快递柜、网游玩家、聊天室中的一员。也可能是微服务中的一个服务,通过netty来实现各服务之间的通信,比如阿里的dubbo就是这样做的。而客户端语言也不一定是java,也可能是c++、web前端、app等,只要支持socket连接,都可以作为客户端。为了快捷测试,可用任意socket或tcp相关工具软件模拟客户端,这里从网上下载SocketTool打开。TCP Client--创建

点击上面的连接按钮,连接按钮变成灰色说明连接成功

取消十六进制格式的勾选,输入hello,发送数据

发出数据hello,并且立即收到hello

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值