netty 入门示例

server 代码

package com.ultrapower.netty.demo1;

import com.ultrapower.netty.Myserver;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class MyServer {
    private int port;
    public MyServer(int port){
        this.port = port;
    }


    public void run() throws InterruptedException {
        // 创建两个线程池对象 一个为服务端对象组 一个为工作对象组
        EventLoopGroup  bossGroup = new NioEventLoopGroup();
        EventLoopGroup  workGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)

                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                             // 这里是进行业务处理的地方
                            socketChannel.pipeline().addLast(new MyServerHandle());
                        }
                    });
            System.out.println("服务端启动ing");
            //异步启动服务端端口
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            // 优雅关闭 释放资源
            channelFuture.channel().closeFuture().sync();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 进行资源的释放
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int port = 8080;
        MyServer myServer = new MyServer(port);
        myServer.run();
    }

}

 

serverHandle 代码

package com.ultrapower.netty.demo1;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.nio.ByteBuffer;

public class MyServerHandle extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuffer = (ByteBuf)msg;
        System.out.println("服务端收到数据:"+byteBuffer.toString(CharsetUtil.UTF_8));
        // 将数据回写回去
        ctx.writeAndFlush(byteBuffer);
    }
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("server accept here channelReadComplete");
    }
     @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
         cause.printStackTrace();
         ctx.close();
    }
}

 

==========================================

client 端代码

  

package com.ultrapower.netty.demo1;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

public class MyNettyClient {
    private String host;
    private int port;

    public MyNettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)

                    .channel(NioSocketChannel.class)

                    .remoteAddress(new InetSocketAddress(host, port))

                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new ClientHandle());
                        }
                    });

            // 客户端同步链接服务端
            ChannelFuture channelFuture = bootstrap.connect().sync();
            // 在这里发生阻塞 直到客户端链接成功
            channelFuture.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }


    public static void main(String[] args) {
        String host = "127.0.0.1";
        int port = 8080;
        new MyNettyClient(host, port).start();
    }
}

 

MyClientHandle 代码

package com.ultrapower.netty.demo1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class ClientHandle extends SimpleChannelInboundHandler<ByteBuf> {
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        System.out.println("client received data : "+byteBuf.toString(CharsetUtil.UTF_8));

    }
    @Override
    public  void channelActive(ChannelHandlerContext ctx){
        System.out.println("ClientHandle channelActive");
        //将数据传输给服务端
        ctx.writeAndFlush(Unpooled.copiedBuffer("this is client", CharsetUtil.UTF_8));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx){
        System.out.println("ClientHandle channelReadComplete");
    }
    @Override
    public void   exceptionCaught(ChannelHandlerContext ctx,Throwable cause){
        cause.printStackTrace();
        ctx.close();
    }


}

 

这样一个基本的回写netty 代码就完成了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值