首页 > 其他分享 >简单实例

简单实例

时间:2022-12-15 11:01:09浏览次数:37  
标签:netty ctx 实例 io 简单 import public channel

一个基础使用方式,方便自己查看。

package com.sora.springboot01.netty;

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

/**
 * @Classname: MyClient
 * @Description:
 * @Author: Stonffe
 * @Date: 2022/11/27 19:33
 */
public class MyClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventExecutors)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new MyClientHandler());
                        }
                    });
            System.out.println("客户端准备完毕,ok");
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6666).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            eventExecutors.shutdownGracefully();
        }
    }
}

package com.sora.springboot01.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.EventExecutorGroup;

/**
 * @Classname: MyClientHandler
 * @Description:
 * @Author: Stonffe
 * @Date: 2022/11/27 19:38
 */
public class MyClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello hello,konichiwa", CharsetUtil.UTF_8));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("收到服务端"+ctx.channel().remoteAddress()+"的消息"+byteBuf.toString(CharsetUtil.UTF_8));
    }
}

package com.sora.springboot01.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @Classname: MyServer
 * @Description:
 * @Author: Stonffe
 * @Date: 2022/11/27 15:32
 */
public class MyServer {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup wokerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,wokerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new MyServerHandler());
                        }
                    });
            System.out.println("服务端已经准备就绪");
            ChannelFuture channelFuture = bootstrap.bind(6666).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            wokerGroup.shutdownGracefully();
        }
    }
}

package com.sora.springboot01.netty;

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

/**
 * @Classname: MyServerHandler
 * @Description:
 * @Author: Stonffe
 * @Date: 2022/11/27 19:24
 */
public class MyServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(msg);
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("收到客户端"+ctx.channel().remoteAddress()+"发送的消息"+byteBuf.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("服务端已收到消息,并发送你一个问号?", CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}

标签:netty,ctx,实例,io,简单,import,public,channel
From: https://www.cnblogs.com/xiaoovo/p/16984488.html

相关文章

  • 简单工厂模式(创建型)
    如何创建一个对象?publicinterfaceProductpublicclassAppleProductpublicclassGoogleProductpublicclassBananaProduct###########################################......
  • 极客编程python入门-类和实例
    类和实例面向对象最重要的概念就是类(Class)和实例(Instance),必须牢记类是抽象的模板,比如Student类,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各......
  • 前端开发系列065-JQuery篇之框架简单介绍
    title:'前端开发系列065-JQuery篇之框架简单介绍'tags:categories:[]date:2018-05-1112:57:52一、jQuery简介jQuery是一款优秀的javaScript库(框架),该框架凭借简洁......
  • 前端开发系列062-网络篇之前端开发Ajax简单介绍
    title:前端开发系列062-网络篇之前端开发Ajax简单介绍tags:categories:[]date:2018-03-2617:05:13一、Ajax技术简单介绍Ajax是一门异步的用于发送网络请求的技术......
  • 一个简单的完整人脸识别系统
    一个简单的完整人脸识别系统from__future__importprint_function#便于测试新版本函数fromtimeimporttime#从time模块导入time,因为有些步骤需要计时importlog......
  • 牛客CSP-J入门组 --- 简单的烦恼
    链接:https://ac.nowcoder.com/acm/problem/25184来源:牛客网题目描述网易云音乐推出了定时关闭播放的功能,假设到了定时关闭播放的时间,当前这首歌......
  • oracle的leading(),use_nl(),index()简单介绍
    使用leading和use_nl可以设置表的查询顺序,来加快查询速度,比如有a,b,c,d四张表,a表的数据最少,如下设置select/*+leading(a)use_nl(a,b,c,d) index(a.id)*/ a.idfro......
  • dremio CommandCreator 简单说明
    CommandCreator主要是基于不同业务规则进行conmandrunner的生成,以下是一个简单说明CommandCreator的作用基于request创建包装的command包装多种conmandrunner(基于......
  • dremio CommandPool简单说明
    CommandPool实际上是一个线程池的处理,官方实现了好几种线程池主要作用限制并行请求以以及job的运行定义优先级任务特点任务基于优先级以及提交时间进行自然排序......
  • ubuntu SMC迁移 后发现 实例内网一直都是原虚机的内网IP
    ubuntuSMC迁移后发现实例内网一直都是原虚机的内网IPipa能看到现在的ECS内网以及原虚机的内网但是ifconfig看只有原虚机的内网IP于是尝试dhclienteth0重启内......