要说的话全在代码里了,直接上代码。
以下内容仅供学习使用,转载请标明出处和作者,并向本人说明。
以下是pom依赖配置
<!--netty-->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.40.Final</version>
</dependency>
以下是server端
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
/**
* @author Blue
* @date Created in 2020/1/13
* @description
*/
@Service
@Slf4j
public class NettyServer {
/**
* 事件循环组,获取连接
*/
private static NioEventLoopGroup bossGroup = new NioEventLoopGroup();
/**
* 工作循环组,处理连接
*/
private static NioEventLoopGroup workerGroup = new NioEventLoopGroup();
/**
* 通过nio方式来接收连接和处理连接
*/
private static ServerBootstrap bootstrap = new ServerBootstrap();
@Autowired
private NettyServerInitializer nettyServerInitializer;
/*** 设置服务端端口 */
@Value("${dms.cloud.netty.port}")
private int port;
@PostConstruct
public void run() {
try {
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
//设置过滤器
.childHandler(nettyServerInitializer)
//设置缓冲池大小,10k
.childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024 * 1024 * 10))
// 维持链接的活跃,清除死链接
.childOption(ChannelOption.SO_KEEPALIVE, true)
//关闭延迟发送
.childOption(ChannelOption.TCP_NODELAY, true);
// 服务器绑定端口监听
ChannelFuture future = bootstrap.bind(port).sync();
// 监听服务器关闭监听
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 关闭EventLoopGroup,释放掉所有资源包括创建的线程
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
@Deprecated
public static void main(String[] args) throws InterruptedException {
try {
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLe