netty之helloword

(1) maven 地址

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty</artifactId>
    <version>3.6.3.Final</version>
</dependency>

(2) 服務(wù)端代碼

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服務(wù)端入門第一個小程序
 */
public class NettyServerDemo {
    public static void main(String[] args) {
        // 服務(wù)類
        ServerBootstrap bootstrap = new ServerBootstrap();

        // 初始化兩個線程池
        // boss線程監(jiān)聽端口,worker線程負責(zé)數(shù)據(jù)讀寫
        ExecutorService boss = Executors.newCachedThreadPool();
        ExecutorService worker = Executors.newCachedThreadPool();

        // 設(shè)置NioServerSocketChannel工廠
        bootstrap.setFactory(new NioServerSocketChannelFactory(boss,worker));

        // 設(shè)置管道工廠
        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服務(wù)開啟了。。。。。。");
    }
}



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;


/** 
* 服務(wù)端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來接受消息,然后在轉(zhuǎn)換成字符串
         *      ChannelBuffer recevie = (ChannelBuffer) e.getMessage();
         *      String msg = new String(recevie.array());
         *解決方法2:在設(shè)置管道的工廠里加入字符串的編碼和解碼
         *      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 = "回復(fù)消息 :" + 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) {
        // 服務(wù)類
        ClientBootstrap bootstrap = new ClientBootstrap();

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

        // 設(shè)置socketChannelFactory工廠
        bootstrap.setFactory(new NioClientSocketChannelFactory(boss,work));

        // 設(shè)置管道工廠
        bootstrap.setPipelineFactory(() -> {
            ChannelPipeline pipeline = Channels.pipeline();

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

            return pipeline;
        });

        // 連接服務(wù)器
        ChannelFuture connect = bootstrap.connect(new InetSocketAddress("127.0.0.1", 20003));

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

        System.out.println("連上服務(wù)器。。。");

        // 測試
        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);
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容