Netty服務端客服端簡單案例

一、引入jar

<!-- https://mvnrepository.com/artifact/io.netty/netty -->
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty</artifactId>
    <version>3.3.0.Final</version>
</dependency>

二、服務端案例代碼 

class ServerHandler extends SimpleChannelHandler {
    // 通道被關閉的時候會觸發
    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelClosed(ctx, e);
        System.out.println("channelClosed");
    }

    // 必須要建立連接,關閉通道的時候纔會觸發
    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelDisconnected(ctx, e);
        System.out.println("channelDisconnected");
    }

    // 接受出現異常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        super.exceptionCaught(ctx, e);
        System.out.println("exceptionCaught");
    }

    // 接受客戶端數據..
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        super.messageReceived(ctx, e);
        System.out.println("messageReceived");
        System.out.println("服務器獲取客戶端發來的參數:" + e.getMessage());
        ctx.getChannel().write("你好啊!");
    }
}
/**
 * @program: zhq_netty
 * @description:
 * @author: HQ Zheng
 * @create: 2019-09-25 15:43
 */
// netty 服務器端
public class NettyServer {
    public static void main(String[] args) {
        // 1.創建服務對象
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 2.創建兩個線程池 第一個 監聽端口號 nio監聽
        ExecutorService boos = Executors.newCachedThreadPool();
        ExecutorService wook = Executors.newCachedThreadPool();
        // 3.將線程池放入工程
        serverBootstrap.setFactory(new NioServerSocketChannelFactory(boos, wook));
        // 4.設置管道工程
        serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            // 設置管道
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = org.jboss.netty.channel.Channels.pipeline();
                // 傳輸數據的時候直接爲string類型
                pipeline.addLast("decoder", new StringDecoder());
                pipeline.addLast("encoder", new StringEncoder());
                // 設置事件監聽類
                pipeline.addLast("serverHandler", new ServerHandler());
                return pipeline;

            }
        });
        // 綁定端口號
        serverBootstrap.bind(new InetSocketAddress(8080));
        System.out.println("服務器端已經被啓動.....");
    }
}

測試是否正常運行

訪問:

 

三、客戶端代碼

class ClientHandler extends SimpleChannelHandler{

    // 通道被關閉的時候會觸發
    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelClosed(ctx, e);
        System.out.println("channelClosed");
    }

    // 必須要建立連接,關閉通道的時候纔會觸發
    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelDisconnected(ctx, e);
        System.out.println("channelDisconnected");
    }

    // 接受出現異常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        super.exceptionCaught(ctx, e);
        System.out.println("exceptionCaught");
    }

    // 接受客戶端數據..
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        super.messageReceived(ctx, e);
        System.out.println("messageReceived");
        System.out.println("服務器向客戶端回覆的內容:" + e.getMessage());
    }
}
/**
 * @program: zhq_netty
 * @description: netty客戶端
 * @author: HQ Zheng
 * @create: 2019-09-25 15:53
 */
public class NettyClient {

    public static void main(String[] args) {
        // 1.創建服務對象
        ClientBootstrap clientBootstrap = new ClientBootstrap();
        // 2.創建兩個線程池 第一個 監聽端口號 nio監聽
        ExecutorService boos = Executors.newCachedThreadPool();
        ExecutorService wook = Executors.newCachedThreadPool();
        // 3.將線程池放入工程
        clientBootstrap.setFactory(new NioClientSocketChannelFactory(boos, wook));
        // 4.設置管道工程
        clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            // 設置管道
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = org.jboss.netty.channel.Channels.pipeline();
                // 傳輸數據的時候直接爲string類型
                pipeline.addLast("decoder", new StringDecoder());
                pipeline.addLast("encoder", new StringEncoder());
                // 設置事件監聽類
                pipeline.addLast("clientHandler", new ClientHandler());
                return pipeline;

            }
        });
        // 綁定端口號
        ChannelFuture connect = clientBootstrap.connect(new InetSocketAddress("127.0.0.1", 8080));
        Channel channel = connect.getChannel();
        System.out.println("client start");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("請輸入內容:");
            channel.write(scanner.next());

        }
    }
}

 四、測試驗證

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章