netty服务端开发-I/O处理

使用netty开发服务端程序,主要包括一个服务端程序类,主要负责监听端口,建立连接;还有一个服务端数据处理类,负责处理服务端接收到的业务数据,并进行响应,

先贴上一段负责处理接收数据的demo类

package com.jd.time.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.Date;

/**
 * Created by caozhifei on 2015/4/11.
 */
public class TimeServerHandler extends ChannelHandlerAdapter{
    @Override
    public void channelRead(ChannelHandlerContext context,Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req,"GBK");
        System.out.println("The time server receive order :"+body);
        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date().toString() : "BAD ORDER";
        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
        context.write(resp);
    }
    @Override
    public void channelReadComplete(ChannelHandlerContext context) throws Exception{
        context.flush();
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext context,Throwable cause){
        context.close();
    }
}

TimeServerHandler 是通过继承ChannelHandlerAdapter这个类,但是也可以实现netty提供的一个接口ChannelHandler,但是通过继承我们可以有选择性的通过覆盖父类的方法来实现自己的业务逻辑,不用全部实现接口里边的方法,

它对于网络事件进行读写操作,通常我们只需要关注channelRead和exceptionCaught方法。channelRead方法负责冲通道中读取数据,并进行业务逻辑处理,处理完成之后然后再通过ChannelHandlerContext的write方法异步发送应答信息给客户端;channelReadCommplete中的flush方法,则是将消息发送队列中的消息写入到SocketChannel中发送给对方,当发生异常时,则通过exceptionCaught中的方法释放ChannelHandlerContext相关联的句柄资源等,并且进行日志的详细记录。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值