用java netty nio 写一个tcpserver
时间: 2024-03-16 10:48:00 浏览: 21
好的,以下是一个使用Java Netty NIO编写的TCP服务器的基本示例代码:
```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 TCPServer {
private final int port;
public TCPServer(int port) {
this.port = port;
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup 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 TCPServerHandler());
}
});
ChannelFuture f = b.bind(port).sync();
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port = Integer.parseInt(args[0]);
new TCPServer(port).run();
}
}
```
在这个示例中,我们使用了Java Netty框架,它提供了一种快速构建网络应用程序的方式。我们创建了一个名为“TCPServer”的类,它包含一个构造函数和三个方法:run(),main()和一个自定义的“TCPServerHandler”类。
在“run()”方法中,我们创建了两个事件循环组:bossGroup和workerGroup。bossGroup接受来自客户端的连接,workerGroup负责处理实际的I/O操作。然后,我们创建了一个ServerBootstrap实例,并将bossGroup和workerGroup分别设置为其组。接下来,我们指定了服务器通道类型(NioServerSocketChannel),并设置了一个ChannelInitializer,该初始化程序将添加一个自定义的TCPServerHandler来处理来自客户端的消息。
在“main()”方法中,我们将创建一个新的TCPServer实例,并调用其“run()”方法。在该方法中,我们绑定服务器到指定的端口,并等待直到服务器通道关闭。
最后,我们有一个自定义的“TCPServerHandler”类,它实现了Netty的ChannelInboundHandler接口。该处理程序将处理来自客户端的消息,并在收到消息时向客户端发送响应。以下是该处理程序类的示例代码:
```java
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class TCPServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf in = (ByteBuf) msg;
try {
while (in.isReadable()) {
System.out.print((char) in.readByte());
System.out.flush();
}
} finally {
in.release();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
```
在这个示例中,我们实现了Netty的ChannelInboundHandler接口,并重写了其中的“channelRead()”和“exceptionCaught()”方法。在“channelRead()”方法中,我们接收来自客户端的消息,并将其打印到控制台。在“exceptionCaught()”方法中,我们捕获任何异常并关闭通道。
这就是一个简单的Java Netty NIO TCP服务器的基本示例。