netty应用2------------------server端开发

本文档介绍了如何使用Netty框架实现一个简单的服务器端业务处理类MyEchoServerHandle,涉及channelRead、channelReadComplete和exceptionCaught方法,展示了客户端数据接收、服务器响应以及错误处理的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.extends ChannelInboundHandlerAdapter

代码如下(示例):

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;


/**
 * server端自己的业务处理类
 */
@ChannelHandler.Sharable
public class MyEchoServerHandle extends ChannelInboundHandlerAdapter {
    /*
    * 客户端读到数据以后就会执行
    * */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("server accept: "+byteBuf.toString(CharsetUtil.UTF_8));
        ctx.write(byteBuf);
    }

    /**
     * 服务器端读完以后的处理
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                .addListener(ChannelFutureListener.CLOSE);
    }


    /**
     * 发生异常后的处理
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

2.server代码

代码如下(示例):

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class MyEchoServer {
    private int port;

    public MyEchoServer(int port) {
        this.port = port;
    }
    public void start() throws InterruptedException {
        final MyEchoServerHandle handle = new MyEchoServerHandle();
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            ServerBootstrap strap = new ServerBootstrap();
            strap.group(group)
            		.channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch) throws 			Exception {
                            /*添加到该子channel的pipeline的尾部*/
                            ch.pipeline().addLast(handle);
                        }
                    });
            ChannelFuture future = strap.bind().sync();
            future.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully().sync();/*优雅关闭线程组*/
        }

    }

    public static void main(String[] args) throws InterruptedException {
        MyEchoServer myEchoServer = new MyEchoServer(9090);
        System.out.println("服务器启动-------------");
        myEchoServer.start();
        System.out.println("服务器关闭-------------");

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值