【Netty系列】使用Netty搭建TcpServer

使用Netty搭建TcpServer

  1. 与WebSocketServer(TextWebSocketFrame)和HttpServer(HttpObject)不同,Tcp接受消息使用ByteBuf。

引入netty的依赖

 <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.75.Final</version>
        </dependency>

搭建TcpServer

public class TcpServer {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new TcpServerHandler());
                        }
                    }); //自定义一个初始化类
            ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
            channelFuture.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

创建Tcp消息接收处理器

public class TcpServerHandler extends SimpleChannelInboundHandler<ByteBuf>{
    private int count;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {

        byte[] buffer = new byte[msg.readableBytes()];
        msg.readBytes(buffer);

        //将buffer转成字符串
        String message = new String(buffer, Charset.forName("utf-8"));

        System.out.println("服务器接收到数据 " + message);
        System.out.println("服务器接收到消息量=" + (++this.count));

        //服务器回送数据给客户端, 回送一个随机id ,
        ByteBuf responseByteBuf = Unpooled.copiedBuffer(UUID.randomUUID().toString() + " ", Charset.forName("utf-8"));
        ctx.writeAndFlush(responseByteBuf);

    }
}

使用NetAssit网络调试助手发送消息

客户端发送消息

在这里插入图片描述

服务端接收消息并回复

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个使用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服务器的基本示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值