Netty来创建一个TCP服务器,分包上传语音文件的处理
创建一个TCP服务器。
我们以在Spring Boot项目中集成Netty来创建一个TCP服务器为例,使用Netty创建一个TCP服务器是常见且可靠的,特别是在需要高性能、低延迟的网络通信时。
添加依赖
在pom.xml文件中添加Netty的依赖:
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.68.Final</version>
</dependency>
</dependencies>
创建Netty服务器配置类
创建一个配置类来启动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.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Configuration
public class NettyServerConfig {
private final int port = 8080;
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
private ChannelFuture channelFuture;
@PostConstruct
public void start() throws Exception {
bossGroup = new NioEventLoopGroup(1);
workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new StringEncoder());
ch.pipeline().addLast(new SessionIdHandler());
ch.pipeline().addLast(new NettyServerHandler());
ch.pipeline().addLast(new NettyServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
channelFuture = b.bind(port).sync();
System.out.println("Netty server started on port " + port);
} finally {
if (channelFuture != null && channelFuture.isSuccess()) {
channelFuture.channel().closeFuture().sync();
}
}
}
@PreDestroy
public void stop() throws Exception {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
创建Netty处理器
添加会话ID Handler
创建一个服务来管理这个映射,并在Netty