netty之helloword

(1) maven 地址


    io.netty
    netty
    3.6.3.Final


(2) 服务端代码

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Netty服务端入门第一个小程序
 */
public class NettyServerDemo {
    public static void main(String[] args) {
        // 服务类
        ServerBootstrap bootstrap = new ServerBootstrap();

        // 初始化两个线程池
        // boss线程监听端口,worker线程负责数据读写
        ExecutorService boss = Executors.newCachedThreadPool();
        ExecutorService worker = Executors.newCachedThreadPool();

        // 设置NioServerSocketChannel工厂
        bootstrap.setFactory(new NioServerSocketChannelFactory(boss,worker));

        // 设置管道工厂
        bootstrap.setPipelineFactory(() -> {
            ChannelPipeline pipeline = Channels.pipeline();

            pipeline.addLast("encode", new StringEncoder());
            pipeline.addLast("decode", new StringDecoder());
            pipeline.addLast("firstHandler", new ServerChannelHandler());

            return pipeline;
        });

        // 绑定端口
        bootstrap.bind(new InetSocketAddress(20003));

        System.out.println("netty服务开启了。。。。。。");
    }
}



import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;


/** 
* 服务端ChannelHandler
 */
public class ServerChannelHandler extends SimpleChannelHandler {
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        super.messageReceived(ctx, e);

        System.out.println("=======messageReceived=======");
        /**
         * 直接这么接受字符串会报错
         * String msg = (String) e.getMessage();
         *
         * 警告: EXCEPTION, please implement com.young.socket.ch2.FirstChannelHandler.exceptionCaught() for proper handling.
         * java.lang.ClassCastException: org.jboss.netty.buffer.BigEndianHeapChannelBuffer cannot be cast to java.lang.String
         *
         * 解决方法1:使用ChannelBuffer来接受消息,然后在转换成字符串
         *      ChannelBuffer recevie = (ChannelBuffer) e.getMessage();
         *      String msg = new String(recevie.array());
         *解决方法2:在设置管道的工厂里加入字符串的编码和解码
         *      pipeline.addLast("encode", new StringEncoder());
         *      pipeline.addLast("decode", new StringDecoder());
         */
//        ChannelBuffer recevie = (ChannelBuffer) e.getMessage();
//        String msg = new String(recevie.array());
        String msg = (String) e.getMessage();
        System.out.println("接受消息 :" + msg);

//        String result = "hi, yi shou dao ";
//        ChannelBuffer replay = ChannelBuffers.copiedBuffer(result.getBytes());
        String replay = "回复消息 :" + msg + ", thanks.....";
        ctx.getChannel().write(replay);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        super.exceptionCaught(ctx, e);
        System.out.println("=======exceptionCaught=======");
    }

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelConnected(ctx, e);
        System.out.println("=======channelConnected=======");
    }

    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelDisconnected(ctx, e);
        System.out.println("=======channelDisconnected=======");
    }

    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("=======channelClosed=======");
        super.channelClosed(ctx, e);
    }
}

(3)  客户端代码

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *  Netty客户端入门第一个小程序
 */
public class NettyClientDemo {
    public static void main(String[] args) {
        // 服务类
        ClientBootstrap bootstrap = new ClientBootstrap();

        // 线程池
        ExecutorService boss = Executors.newCachedThreadPool();
        ExecutorService work = Executors.newCachedThreadPool();

        // 设置socketChannelFactory工厂
        bootstrap.setFactory(new NioClientSocketChannelFactory(boss,work));

        // 设置管道工厂
        bootstrap.setPipelineFactory(() -> {
            ChannelPipeline pipeline = Channels.pipeline();

            pipeline.addLast("decoder", new StringDecoder());
            pipeline.addLast("encoder", new StringEncoder());
            pipeline.addLast("clientHandler", new ClientChannelHandler());

            return pipeline;
        });

        // 连接服务器
        ChannelFuture connect = bootstrap.connect(new InetSocketAddress("127.0.0.1", 20003));

        // 得到channel
        Channel channel = connect.getChannel();

        System.out.println("连上服务器。。。");

        // 测试
        Scanner scanner = new Scanner(System.in);
        while (true){
            System.out.println("请说话:");
            channel.write(scanner.nextLine());
        }
    }
}

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;


/**
 * 客户端 ChannelHandler
 */
public class ClientChannelHandler extends SimpleChannelHandler {
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        super.messageReceived(ctx, e);
        System.out.println("==========messageReceived===============");
        System.out.println(e.getMessage());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        super.exceptionCaught(ctx, e);
        System.out.println("=======exceptionCaught=======");
    }

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelConnected(ctx, e);
        System.out.println("=======channelConnected=======");
    }

    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelDisconnected(ctx, e);
        System.out.println("=======channelDisconnected=======");
    }

    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("=======channelClosed=======");
        super.channelClosed(ctx, e);
    }
}

你可能感兴趣的:(netty之helloword)