java 使用netty搭建tcp服务器(hello world)
时间: 2023-08-06 12:06:52 浏览: 124
好的,以下是使用Netty搭建TCP服务器的示例代码(Hello World):
```java
import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;
public class HelloWorldServer {
private final int port;
public HelloWorldServer(int port) {
this.port = port;
}
public void run() throws Exception {
// 创建两个 EventLoopGroup,一个用于接收客户端连接,一个用于处理客户端请求
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
// 创建 ServerBootstrap 对象,用于配置服务器
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 HelloWorldServerHandler());
}
});
// 绑定端口,开始接收客户端请求
ChannelFuture f = b.bind(port).sync();
// 等待服务器 socket 关闭
f.channel().closeFuture().sync();
} finally {
// 释放资源
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port = 8080;
new HelloWorldServer(port).run();
}
}
```
其中,`HelloWorldServerHandler` 是自定义的消息处理器,可以根据需要进行处理。
阅读全文