Netty实战的第13章UDP client

LogEventDecoder

package com.xmg.nnetty.udp.client;

import java.util.List;

import com.xmg.nnetty.udp.LogEvent;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.util.CharsetUtil;

public class LogEventDecoder extends MessageToMessageDecoder<DatagramPacket>{
    @Override
    protected void decode(ChannelHandlerContext ctx, DatagramPacket datagramPacket, List<Object> out) throws Exception {
        ByteBuf data = datagramPacket.content();
        int idex = data.indexOf(0, data.readableBytes(), LogEvent.SEPARATOR);
        String fileName = data.slice(0, idex).toString(CharsetUtil.UTF_8);
        String logMsg = data.slice(idex+1, data.readableBytes()).toString(CharsetUtil.UTF_8);
        LogEvent event = new LogEvent(datagramPacket.sender(),System.currentTimeMillis(),fileName,logMsg);
        out.add(event);
    }

}

LogEventHandler

package com.xmg.nnetty.udp.client;

import java.nio.charset.Charset;

import com.xmg.nnetty.udp.LogEvent;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

public class LogEventHandler extends SimpleChannelInboundHandler<LogEvent>{
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LogEvent msg) throws Exception {
        StringBuilder builder = new StringBuilder();
        builder.append(msg.getReceived());
        builder.append(" [");
        builder.append(msg.getAddress().toString());
        builder.append("] ");
        builder.append(msg.getLogfile());
        builder.append(": ");
        builder.append(msg.getMsg());
        System.out.println(builder.toString());
    }

    @Override
    public boolean acceptInboundMessage(Object msg) throws Exception {
        // TODO Auto-generated method stub
        return super.acceptInboundMessage(msg);
    }

//    @Override
//    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        System.out.println("channleRead");
//        System.out.println(((DatagramPacket)msg).content().getCharSequence(0, 12,Charset.defaultCharset() ));
//        //super.channelRead(ctx, msg);
//    }
//
//    @Override
//    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        System.out.println("channelActive");
//        super.channelActive(ctx);
//    }
//
//    @Override
//    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
//        System.out.println("channelInactive");
//        super.channelInactive(ctx);
//    }
    
    
}

LogEventMonitor

package com.xmg.nnetty.udp.client;

import java.net.InetSocketAddress;

import com.xmg.nnetty.udp.LogEvent;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

public class LogEventMonitor {
    private final EventLoopGroup group;
    private final Bootstrap strap;
    
    public LogEventMonitor(InetSocketAddress address) {
        group = new NioEventLoopGroup();
        strap = new Bootstrap();
        strap.group(group).channel(NioDatagramChannel.class)
        .option(ChannelOption.SO_BROADCAST, true).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new LogEventDecoder());
                pipeline.addLast(new LogEventHandler());
            }
            
        }).localAddress(address);
    }
    
    
    public Channel bind() {
        return strap.bind().syncUninterruptibly().channel();
    }
    
    
    public void stop() {
        group.shutdownGracefully();
    }
    
    public static void main(String[] args) throws Exception {
        LogEventMonitor monitor  = new LogEventMonitor(new InetSocketAddress(9001));
        try {
            Channel channel = monitor.bind();
            System.out.println("client running");
            channel.closeFuture().sync();
        }finally {
            monitor.stop();
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值