本文主要是介绍Java - Apache Mina 自定义协议通信,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、定义协议实体
import java.nio.charset.Charset;/*** 自定义协议的消息体*/
public class MyMsg {/*** 消息长度*/private Integer lenth;/*** 发送人*/private Long sender;/*** 接收人*/private Long receiver;/*** 消息内容*/private String content;public MyMsg() {}public Long getSender() {return sender;}public void setSender(Long sender) {this.sender = sender;}public Long getReceiver() {return receiver;}public void setReceiver(Long receiver) {this.receiver = receiver;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}/*** 先计算长度,再返回。这里长度包含长度本身的字节*/public Integer getLenth() {this.lenth = 4 + 8*2 + this.content.getBytes(Charset.forName("utf-8")).length;return lenth;}public MyMsg(Long sender, Long receiver, String content) {this.sender = sender;this.receiver = receiver;this.content = content;}@Overridepublic String toString() {return "MyMsg [lenth=" + this.getLenth() + ", sender=" + sender + ", receiver="+ receiver + ", content=" + content + "]";}}
二、定义编解码器
1、编码器
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;/*** 编码器 */
public class MyEncoder extends ProtocolEncoderAdapter {@Overridepublic void encode(IoSession session, Object message, ProtocolEncoderOutput encoderOutput)throws Exception {CharsetEncoder ce = Charset.forName("utf-8").newEncoder();MyMsg msg = (MyMsg) message;// Mina IoBufferIoBuffer buffer = IoBuffer.allocate(100).setAutoExpand(true);buffer.putInt(msg.getLenth());buffer.putLong(msg.getSender());buffer.putL
这篇关于Java - Apache Mina 自定义协议通信的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!