() { @Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new YourDecoderHandler()); // 添加解码器
ch.pipeline().addLast(new YourEncoderHandler()); // 添加编码器
ch.pipeline().addLast(new Your业务逻辑Handler()); // 添加业务逻辑处理器
}
});
```
绑定端口与启动服务
```java
ChannelFuture f = b.bind(port).sync();
f.channel().closeFuture().sync();
```
处理异常与关闭
添加异常捕获机制,确保服务稳定运行,并在关闭时正确释放资源。
四、示例代码(完整服务器)
```java
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class NettyServer {
private int port;
public NettyServer(int port) {
this.port = port;
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer() { @Override
protected void initChannel(SocketChannel ch) {
ch.pipeline().addLast(new YourDecoderHandler());
ch.pipeline().addLast(new YourEncoderHandler());
ch.pipeline().addLast(new YourBusinessLogicHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 1024);
ChannelFuture f = b.bind(port).sync();
System.out.println("Server started on port " + port);
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port = 8080; // 监听端口
new NettyServer(port).run();
}
}
```
五、优化建议
线程池调优
根据服务器硬件配置调整`bossGroup`和`workerGroup`的核心线程数和最大线程数。
资源管理
使用`try-with-resources`或`finally`块确保Channel正确关闭,避免资源泄漏。
协议扩展
可集成Protobuf、Kryo等编解码器,或自定义协议处理器。
通过以上步骤,可快速