Netty学习笔记(一)—— Netty Demo

服务端代码:

package com.linfo.netty.helloExample;

import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

/**
 * Created by linfeng
 */
public class serverDemo {

    private int port;

    public serverDemo(int port) {
        this.port = port;
    }

    public static void main(String[] args) {
        new serverDemo(8088).start();
    }

    public void start() {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap = bootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress(port))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    public void initChannel(SocketChannel channel) throws Exception {
                        channel.pipeline().addLast(new helloHandler());
                    }
                });

        try {
            ChannelFuture future = bootstrap.bind(port).sync();
            System.out.println("listen port: " + port);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }

    }

    @ChannelHandler.Sharable
    class helloHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext context, Object msg) {
            ByteBuf in = (ByteBuf) msg;
            System.out.println("server received a message...");
            System.out.println(context.channel().remoteAddress() + " -> server : " + in.toString(CharsetUtil.UTF_8));
            context.write("server has received message server -> client : " + in.toString(CharsetUtil.UTF_8) );
            context.flush();
            System.out.flush();
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext context) {
            context.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
            cause.printStackTrace();
            context.close();
        }
    }

}

客户端代码:

package com.linfo.netty.helloExample;

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.CharsetUtil;

import java.net.InetSocketAddress;

/**
 * Created by linfeng
 */
public class clientDemo {
    private final static String HOST = "127.0.0.1";
    private final static int PORT = 8088;

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

    public void start() {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap = bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(HOST, PORT))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel channel) {
                            channel.pipeline().addLast(new helloClientHandler());
                        }
                    });
            ChannelFuture future = bootstrap.connect().sync();
            //future.channel().writeAndFlush("Hello server this is a message, I am Client");
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    @ChannelHandler.Sharable
    class helloClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
        @Override
        public void channelActive(ChannelHandlerContext channelHandlerContext) {
            channelHandlerContext.writeAndFlush(Unpooled.copiedBuffer("First message", CharsetUtil.UTF_8));
        }

        @Override
        public void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
            System.out.println("Client received:" + byteBuf.toString(CharsetUtil.UTF_8));
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable cause) {
            cause.printStackTrace();
            channelHandlerContext.close();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_23016999/article/details/82113999