netty入门启动

maven

		<dependency>
			<groupId>io.netty</groupId>
			<artifactId>netty-all</artifactId>
			<version>${netty.version}</version>
		</dependency>

netty启动类

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NioServer {
	public static void main(String[] args) {
		new NioServer().start();
	}
	private void start() {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(group)
			.channel(NioServerSocketChannel.class)
			.localAddress(8888)
			.childHandler(new ChannelInitializer<Channel>() {
				@Override
				protected void initChannel(Channel ch) throws Exception {
					ch.pipeline()
					//这里添加处理器
					.addLast(new MyNioServerHandler());
						
				}
			});
			ChannelFuture future = bootstrap.bind().sync();
			
			System.out.println("=======netty启动");
			future.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			group.shutdownGracefully();
		}

	}
}

所有的启动类基本上都一致,复制即可.
需要注意的是,本类启动了8888端口作为netty的接收端口.
其次,在addLast(new MyNioServerHandler());这里,添加了一个处理器叫做MyNioServerHandler,其实pipeline这里是处理器链,仍然可以添加其他处理器.
MyNioServerHandler是自定义的处理器,我们看一个简单的例子

简单处理器

import java.nio.charset.Charset;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class MyNioServerHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

		ByteBuf bb = (ByteBuf) msg;
		String msgStr = bb.toString(Charset.forName("UTF-8")); 这个相当于转成字符串
		System.out.println("read " + msgStr);//打印发来的东西
		ctx.writeAndFlush(msg);//把发来的消息再返回去
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		System.out.println("========异常");
		super.exceptionCaught(ctx, cause);
	}

}

网络传输发来的都是字节数组,但是netty做了封装,默认发来的都是ByteBuf
接下来运行netty启动类的main方法,就启动了一个服务器.
然后用二进制发送接收工具发送即可,就会接到和发送相同的消息.


如果是Stringboot项目可以这样做.做个异步,否则netty会阻塞主线程

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.6.Final</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
     </dependencies>
@Slf4j
@Component
public class NioServer {
    @Value("${netty.port}")
    private int port;

    @Async
    public void start() {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(group)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(port)
                    .childHandler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel ch) throws Exception {
                            ch.pipeline()
                            .addLast(new StringEncoder())
                            .addLast(new MyNioServerHandler());

                        }
                    });
  
            bootstrap.bind().sync().channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }

    }
}
@EnableAsync
@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args).getBean(NioServer.class).start();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值