HelloServerHandler.java 1.2 KB
Newer Older
武汉红喜's avatar
武汉红喜 已提交
1
package org.hongxi.whatsmars.remoting.transport.netty;
武汉红喜's avatar
武汉红喜 已提交
2 3 4 5 6 7 8 9 10 11 12

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

import java.util.Date;

/**
 * Created by shenhongxi on 2018/10/5.
 */
武汉红喜's avatar
武汉红喜 已提交
13
public class HelloServerHandler extends ChannelInboundHandlerAdapter {
武汉红喜's avatar
武汉红喜 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, "UTF-8");
        System.out.println("The time server receive command : " + body);
        String currentTimes = "QUERY TIME COMMAND".equalsIgnoreCase(body) ? new Date().toString() : "BAD COMMAND";
        ByteBuf resp = Unpooled.copiedBuffer(currentTimes.getBytes());
        ctx.write(resp);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

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