Netty——基本使用介绍

private int port;

public Server(int port) {

this.port = port;

}

public void run() {

EventLoopGroup bossGroup = new NioEventLoopGroup(); //用于处理服务器端接收客户端连接

EventLoopGroup workerGroup = new NioEventLoopGroup(); //进行网络通信(读写)

try {

ServerBootstrap bootstrap = new ServerBootstrap(); //辅助工具类,用于服务器通道的一系列配置

bootstrap.group(bossGroup, workerGroup) //绑定两个线程组

.channel(NioServerSocketChannel.class) //指定NIO的模式

.childHandler(new ChannelInitializer() { //配置具体的数据处理方式

@Override

protected void initChannel(SocketChannel socketChannel) throws Exception {

System.out.println(Thread.currentThread().getName() + “,服务器初始化通道…”);

/* ByteBuf delimiter = Unpooled.copiedBuffer(“$_”.getBytes());

socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));

socketChannel.pipeline().addLast(new StringDecoder());*/

socketChannel.pipeline().addLast(new ServerHandler());

}

})

/**

  • 对于ChannelOption.SO_BACKLOG的解释:

  • 服务器端TCP内核维护有两个队列,我们称之为A、B队列。客户端向服务器端connect时,会发送带有SYN标志的包(第一次握手),服务器端

  • 接收到客户端发送的SYN时,向客户端发送SYN ACK确认(第二次握手),此时TCP内核模块把客户端连接加入到A队列中,然后服务器接收到

  • 客户端发送的ACK时(第三次握手),TCP内核模块把客户端连接从A队列移动到B队列,连接完成,应用程序的accept会返回。也就是说accept

  • 从B队列中取出完成了三次握手的连接。

  • A队列和B队列的长度之和就是backlog。当A、B队列的长度之和大于ChannelOption.SO_BACKLOG时,新的连接将会被TCP内核拒绝。

  • 所以,如果backlog过小,可能会出现accept速度跟不上,A、B队列满了,导致新的客户端无法连接。要注意的是,backlog对程序支持的

  • 连接数并无影响,backlog影响的只是还没有被accept取出的连接

*/

.option(ChannelOption.SO_BACKLOG, 128) //设置TCP缓冲区

.option(ChannelOption.SO_SNDBUF, 32 * 1024) //设置发送数据缓冲大小

.option(ChannelOption.SO_RCVBUF, 32 * 1024) //设置接受数据缓冲大小

.childOption(ChannelOption.SO_KEEPALIVE, true); //保持连接

ChannelFuture future = bootstrap.bind(port).sync();

future.channel().closeFuture().sync();

} catch (Exception e) {

e.printStackTrace();

} finally {

workerGroup.shutdownGracefully();

bossGroup.shutdownGracefully();

}

}

public static void main(String[] args) {

new Server(8379).run();

}

}

ServerHandler类:

package com.zh.springboot_netty.netty;

import io.netty.buffer.ByteBuf;

import io.netty.buffer.Unpooled;

import io.netty.channel.ChannelHandlerContext;

import io.netty.channel.ChannelInboundHandlerAdapter;

public class ServerHandler extends ChannelInboundHandlerAdapter {

@Override

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

//do something msg

ByteBuf buf = (ByteBuf)msg;

byte[] data = new byte[buf.readableBytes()];

buf.readBytes(data);

String request = new String(data, “utf-8”);

System.out.println("Server: " + request);

//写给客户端

String response = “我是反馈的信息”;

ctx.writeAndFlush(Unpooled.copiedBuffer(“888”.getBytes()));

//.addListener(ChannelFutureListener.CLOSE);

}

@Override

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

cause.printStackTrace();

ctx.close();

}

}

客户端:

package com.zh.springboot_netty.netty;

import io.netty.bootstrap.Bootstrap;

import io.netty.buffer.ByteBuf;

import io.netty.buffer.Unpooled;

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.SocketChannel;

import io.netty.channel.socket.nio.NioSocketChannel;

import io.netty.handler.codec.DelimiterBasedFrameDecoder;

import io.netty.handler.codec.string.StringDecoder;

/*

客户端

*/

public class Client {

public static void main(String[] args) throws InterruptedException {

EventLoopGroup workerGroup = new NioEventLoopGroup();

Bootstrap bootstrap = new Bootstrap();

bootstrap.group(workerGroup)

.channel(NioSocketChannel.class)

.handler(new ChannelInitializer() {

@Override

protected void initChannel(SocketChannel socketChannel) throws Exception {

System.out.println(Thread.currentThread().getName() + “,客户端初始化管道…”);

/* ByteBuf delimiter = Unpooled.copiedBuffer(“$_”.getBytes());

socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter));

socketChannel.pipeline().addLast(new StringDecoder());*/

socketChannel.pipeline().addLast(new ClientHandler());

}

});

ChannelFuture future = bootstrap.connect(“127.0.0.1”, 8379).sync();

future.channel().writeAndFlush(Unpooled.copiedBuffer(“777”.getBytes()));

future.channel().closeFuture().sync();

workerGroup.shutdownGracefully();

}

}

ClientHandler类:

package com.zh.springboot_netty.netty;

import io.netty.buffer.ByteBuf;

import io.netty.channel.ChannelHandlerAdapter;

import io.netty.channel.ChannelHandlerContext;

import io.netty.channel.ChannelInboundHandlerAdapter;

import io.netty.util.ReferenceCountUtil;

public class ClientHandler extends ChannelInboundHandlerAdapter {

@Override

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

try {

ByteBuf buf = (ByteBuf) msg;

byte[] data = new byte[buf.readableBytes()];

buf.readBytes(data);

System.out.println(“Client:” + new String(data).trim());

/* String str = (String) msg;

System.out.println(str);*/

} finally {

ReferenceCountUtil.release(msg);

}

}

@Override

public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

cause.printStackTrace();

ctx.close();

}

}

运行结果:

最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助。

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,不论你是刚入门Java开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

[外链图片转存中…(img-UXNOaKNo-1715853724093)]

[外链图片转存中…(img-odv9CdVi-1715853724093)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,不论你是刚入门Java开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门!

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值