Netty 5.x 1.netty服务器搭建

一个简单的Netty服务  接收什么信息就回复什么信息

总目录

Netty 5.x  1.netty服务器搭建

Netty 5.x 2.自定义编解码器

Maven依赖

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>5.0.0.Alpha2</version>
</dependency>

创建服务 并绑定端口

public class Server extends Thread{
	private int port = -1;
	
	public Server(int port) {
		this.port = port;
	}
	
	@Override
	public void run() {
		bind(port);
	}
	
	private void bind(int port) {
		EventLoopGroup boss = new NioEventLoopGroup(1);
		EventLoopGroup work = new NioEventLoopGroup();

		ServerBootstrap bootstrap =  new ServerBootstrap();
		try {
			bootstrap.group(boss, work)
			.channel(NioServerSocketChannel.class)//注册factory
			.childHandler(new ChannelInitializer<Channel>() {//注册piepline
				@Override
				protected void initChannel(Channel sc) throws Exception {//初始化连接
					sc.pipeline().addLast(new ServerHandle());			//添加处理网络io类
				}
			})
			.option(ChannelOption.SO_BACKLOG, 128)
			.childOption(ChannelOption.TCP_NODELAY, true)//TCP无掩饰
			.childOption(ChannelOption.SO_KEEPALIVE,true);//清除死连接,维持活跃的
			ChannelFuture future = bootstrap.bind(port);
			future.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }
	}


}

网络io处理类(服务器信息处理器)

public class ServerHandle extends SimpleChannelInboundHandler<ByteBuf>{

	@Override
	protected void messageReceived(ChannelHandlerContext cx, ByteBuf message) throws Exception {
            byte[] b = new byte[message.readableBytes()];
            message.readBytes(b);
            System.out.println(new String(b));
            message.resetReaderIndex();//重置指针
            cx.write(message);
            cx.flush();
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dan淡淡的心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值