【Java】Netty的简单使用

实现的功能:服务端监听8888端口,接收消息后加上’server’然后返回给客户端。
客户端只要连接一建立就向服务端发消息,并等待服务端的返回的消息输出。

首先引入依赖

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

客户端代码

package com.zxh.netty1;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.ReferenceCountUtil;

import java.io.IOException;
import java.net.Socket;

public class Client {
    // 连接服务器
    public void connect(){
        EventLoopGroup group = new NioEventLoopGroup(1);
        Bootstrap b = new Bootstrap();
        try {
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ClientHandler());
                        }
                    });
            ChannelFuture f = b.connect("localhost", 8888).sync();
            f.channel().closeFuture().sync();  // 固定写法 监听channel关闭 同步阻塞主线程 否则无法还未接受到服务器返回的消息程序就已经结束了
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws IOException {
        Client client = new Client();
        client.connect();
    }
}

class ClientHandler extends ChannelInboundHandlerAdapter{
    // channel初始化后就向服务器发送消息
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf buf  = Unpooled.copiedBuffer("hello".getBytes());
        ctx.writeAndFlush(buf);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server return!!!");
        ByteBuf buf = null;
        try {
            buf = (ByteBuf) msg;
            byte[] bytes = new byte[buf.readableBytes()];
            buf.getBytes(buf.readerIndex(),bytes); // 从可读的位置开始,读满整个bytes
            System.out.println(new String(bytes));
        }finally {
            if(buf != null)
                ReferenceCountUtil.release(buf);
        }
    }
    // 所有异常都在这里处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close(); // 一般情况下出现异常就关闭该channel
    }
}

服务端代码

package com.zxh.netty1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.CharsetUtil;

/**
 * Created by zxh on 2022/1/28
 */
public class Server {

    private int port = 8888;

    // 服务器启动
    public void start(){
        // 两个group 相当于两个线程池
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);  // 只负责连接
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(2); // workerGroup会建立一个监听器,可以有自己的处理handle
        ServerBootstrap b = new ServerBootstrap(); // server启动前的配置
        b.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new Handle());
                    }
                });

        try {
            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

}

class Handle extends ChannelInboundHandlerAdapter{
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("Channel Read!!");
        ByteBuf buf = (ByteBuf)msg;
        String s = buf.toString(CharsetUtil.UTF_8);
        s = "server " + s;
        System.out.println(buf.toString(CharsetUtil.UTF_8));
        ByteBuf buf1 = Unpooled.copiedBuffer(s.getBytes());
        ctx.writeAndFlush(buf1);
        super.channelRead(ctx, msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Channel Active!");
    }

    // 所有异常都在这里处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();  // 一般情况下出现异常就关闭该连接
    }
}

不得不说些网络编程代码确实很麻烦。相比于NIO,Netty已经帮我们简化了很多了,但是代码量还是很大。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值