Netty UDP client

package com.ahies.stm.app.electricmodbus;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

public class ChineseProverbClient {
    public void run(int port) throws Exception {
        String cmd = "setr=00000000";
        cmd = "setr=11111111";
        //广播地址
        String host = "255.255.255.255";
//        host = "192.168.41.247";
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChineseProverbClientHandler());
            Channel ch = b.bind(9999).sync().channel();
            //向网段内的所有机器广播
            ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                    cmd, CharsetUtil.UTF_8), new InetSocketAddress(
                    host, port))).sync();
            //客户端等待15s用于接收服务端的应答消息,然后退出并释放资源
            if (!ch.closeFuture().await(15000)) {
                System.out.println("查询超时!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 9128;
        if (args != null && args.length > 0) {
            port = Integer.valueOf(args[0]);
        }
        new ChineseProverbClient().run(port);
    }
}

 

 

package com.ahies.stm.app.electricmodbus;

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

public class ChineseProverbClientHandler extends SimpleChannelInboundHandler {


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

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket) throws Exception {
        String response = datagramPacket.content().toString(CharsetUtil.UTF_8);
            System.out.println(response);
            channelHandlerContext.close();
    }
}

 

你可能感兴趣的:(netty)