Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package cn.isccn.familycloudtv.network;
- import com.google.gson.Gson;
- import java.net.InetSocketAddress;
- import cn.isccn.familycloudtv.bean.Packet;
- import cn.isccn.familycloudtv.utils.Utils;
- import io.netty.buffer.ByteBuf;
- import io.netty.buffer.Unpooled;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.channel.SimpleChannelInboundHandler;
- import io.netty.channel.socket.DatagramPacket;
- import io.netty.util.CharsetUtil;
- import io.netty.util.concurrent.Future;
- import io.netty.util.concurrent.GenericFutureListener;
- import static cn.isccn.familycloudtv.utils.SocketUtils.parsePacket;
- /**
- * Create by hongxin.wen on 2018/7/10
- * <p>
- * 修改记录:
- * DES: 2018/7/6 V1.0 基于Netty框架的UDP通信客户端引导 by hongxin.wen
- */
- public class UDPClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
- @Override
- public void channelActive(ChannelHandlerContext ctx) throws Exception {
- Utils.printLog("client channel is ready!");
- super.channelActive(ctx);
- }
- public static void sendMsg(final String msg, final InetSocketAddress inetSocketAddress) {
- Utils.printLog("udp client send msg!");
- if (msg == null) {
- Utils.printLog("send msg is null");
- throw new NullPointerException("msg is null");
- }
- senderInternal(datagramPacket(msg, inetSocketAddress));
- }
- private static void senderInternal(DatagramPacket datagramPacket) {
- if (UDPClient.channel != null) {
- UDPClient.channel.writeAndFlush(datagramPacket).addListener(new GenericFutureListener<Future<? super Void>>() {
- @Override
- public void operationComplete(Future<? super Void> future) {
- Utils.printLog(" send msg success");
- }
- });
- }
- }
- private static DatagramPacket datagramPacket(String msg, InetSocketAddress inetSocketAddress) {
- ByteBuf buf = Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8);
- return new DatagramPacket(buf, inetSocketAddress);
- }
- @Override
- protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) {
- final ByteBuf buf = msg.content();
- byte[] res = new byte[buf.readableBytes()];
- buf.readBytes(res);
- String result = new String(res, CharsetUtil.UTF_8);
- Gson gson = new Gson();
- Packet packet = gson.fromJson(result, Packet.class);
- parsePacket(packet);
- Utils.printLog("server response result = " + result);
- }
- @Override
- public void channelInactive(ChannelHandlerContext ctx) throws Exception {
- Utils.printLog("conn close!");
- super.channelInactive(ctx);
- }
- }
Add Comment
Please, Sign In to add comment