AppMessageEncoder.java 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * Copyright 2013-2019 Xia Jun(3979434@qq.com).
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. ***************************************************************************************
  17. * *
  18. * Website : http://www.farsunset.com *
  19. * *
  20. ***************************************************************************************
  21. */
  22. package com.fdkk.server.coder;
  23. import com.fdkk.server.constant.CIMConstant;
  24. import com.fdkk.server.model.Transportable;
  25. import io.netty.buffer.ByteBuf;
  26. import io.netty.channel.ChannelHandlerContext;
  27. import io.netty.handler.codec.MessageToByteEncoder;
  28. /**
  29. * 服务端发送消息前编码
  30. */
  31. public class AppMessageEncoder extends MessageToByteEncoder<Transportable> {
  32. @Override
  33. protected void encode(final ChannelHandlerContext ctx, final Transportable data, ByteBuf out){
  34. byte[] body = data.getBody();
  35. byte[] header = createHeader(data.getType(), body.length);
  36. out.writeBytes(header);
  37. out.writeBytes(body);
  38. }
  39. /**
  40. * 创建消息头,结构为 TLV格式(Tag,Length,Value)
  41. * 第一字节为消息类型
  42. * 第二,三字节为消息长度分隔为高低位2个字节
  43. */
  44. private byte[] createHeader(byte type, int length) {
  45. byte[] header = new byte[CIMConstant.DATA_HEADER_LENGTH];
  46. header[0] = type;
  47. header[1] = (byte) (length & 0xff);
  48. header[2] = (byte) ((length >> 8) & 0xff);
  49. return header;
  50. }
  51. }