809 服务端程序

Survive by day and develop by night.
talk for import biz , show your perfect code,full busy,skip hardness,make a better result,wait for change,challenge Survive.
happy for hardess to solve denpendies.

目录

在这里插入图片描述

概述

809 服务端程序:

需求:

设计思路

实现思路分析

1.Byte2MessageDecoder

@Slf4j
public class Byte2MessageDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        byte[] readDatas = new byte[msg.readableBytes()];
        msg.readBytes(readDatas);
        log.info("接收到服务端发送的下行消息:{}", ByteArrayUtil.bytes2HexStr(readDatas));
    }
}

2.Tcp client:

package cn.com.onlinetool.jt809.client;

import cn.com.onlinetool.jt809.util.ByteArrayUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

/**
 * @author choice
 * @date 2019-03-13 14:40
 *
 */
public class JT809TcpClient {
    public void runClient() throws Exception{
        //如果现在客户端不同,那么也可以不实用多线程模式来处理
        //在netty中考虑到代码的统一性,也允许你在客户端设置线程池
        EventLoopGroup group = new NioEventLoopGroup();//创建一个线程池
        try {
            Bootstrap client = new Bootstrap();//创建客户毒案处理程序
            client.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY,true) //允许接收大块的返回数据
                    .handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
//                            socketChannel.pipeline().addLast(new FixedLengthFrameDecoder(100));

                            //自定义分隔符
//                            ByteBuf delimiter = Unpooled.copiedBuffer("11111".getBytes());
//                            socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter));

                            socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
                            socketChannel.pipeline().addLast(new Message2ByteEncoder());
                            socketChannel.pipeline().addLast(new Byte2MessageDecoder());
                            socketChannel.pipeline().addLast(new JT809TcpClientHandler());
                        }
                    });
            ChannelFuture channelFuture = client.connect("127.0.0.1", 11111).sync();//等待连接处理
            channelFuture.addListener(new GenericFutureListener() {
                @Override
                public void operationComplete(Future future) throws Exception {
                    if(future.isSuccess()){
                        System.out.println("服务器连接已经完成,可以确保进行消息准确传输");
//                        channelFuture.channel().write(ByteArrayUtil.hexStr2Bytes("5B000000480000005210010001E24001000100000000000001E2407465737438303900312E37312E3132392E32303100000000000000000000000000000000000000004E8ED9BA5D"));
//                         channelFuture.channel().write(ByteArrayUtil.hexStr2Bytes("5B000000980000000012001A4799A300000000000000000000000063E5A282B2E2413838383838000000000000000000000000000212020000005A02000000002800000000000000000000000000000000000000000000490101000000010400000000030200000000343400000000000000000000000000303030303030303030303000000000303030303030303030303000000000F8535D"));
//
                        try {
                            Thread.sleep(2*1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        channelFuture.channel().write(ByteArrayUtil.hexStr2Bytes("5B000000980000000012001A4799A300000000000000000000000063E5A282B2E2413838383838000000000000000000000000000212020000005A02000000002800000000000000000000000000000000000000000000490101000000010400000000030200000000343400000000000000000000000000303030303030303030303000000000303030303030303030303000000000F8535D"));
//


                    }
                }
            });
            channelFuture.channel().closeFuture().sync();  //等待关闭连接

        }finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new JT809TcpClient().runClient();
    }
}

3.123

package cn.com.onlinetool.jt809.client;

import cn.com.onlinetool.jt809.util.ByteArrayUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**

  • @author choice
  • @description:
  • @date 2019-03-13 15:02

*/
public class JT809TcpClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(“channelActive…”);
// ctx.channel().write(ByteArrayUtil.hexStr2Bytes(
// “5B000000480000005210010001E24001000100000000000001E2407465737438303900312E37312E3132392E32303100000000000000000000000000000000000000004E8ED9BA5D\r\n”
//
//
// ));

    ctx.channel().write(ByteArrayUtil.hexStr2Bytes(
            "123"


    ));
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    System.out.println("channelRead.........." + ByteArrayUtil.bytes2HexStr((byte[])msg));
    super.channelRead(ctx,msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    System.out.println("exceptionCaught..........");
    cause.printStackTrace();
    ctx.close();
}

}

4.demo

public class Message2ByteEncoder extends MessageToByteEncoder {

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf byteBuf) throws Exception {
        byteBuf.writeBytes((byte[]) msg);
        ctx.writeAndFlush(byteBuf);
        byteBuf.release();
    }
}

拓展实现

这里参考:github:简单实现上述流程:
入门级实现:
: 部分源码实现.
: 源码实现

参考资料和推荐阅读

1.暂无

欢迎阅读,各位老铁,如果对你有帮助,点个赞加个关注呗!同时,期望各位大佬的批评指正~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

执于代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值