liurunyu
2023-11-27 c475f9ad3290c2593897736144758b54e2b2f407
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.dy.testClient.tcpConnect;
 
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
 
import java.io.*;
 
public class LocalEncoder extends ProtocolEncoderAdapter {
 
    /**
     * 对数据进行编码,以备网络传输
     */
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws IOException, Exception{
        MinaData minaData = null ;
        if(message instanceof Command){
            minaData = new MinaData() ;
            minaData.setCom((Command)message) ;
        }else{
            minaData = (MinaData) message;
        }
        byte[] bytes1 = getCommandBytes(minaData.getCom());
        byte[] bytes2 = minaData.getAttachment() ;
        int capacity = (bytes1==null?0:bytes1.length) + (bytes2==null?0:bytes2.length) + 8;
        IoBuffer buffer = IoBuffer.allocate(capacity, false);
        buffer.putInt(bytes1.length);
        buffer.put(bytes1);
        if(bytes2 == null){
            buffer.putInt(0);
        }else{
            buffer.putInt(bytes2.length);
            buffer.put(bytes2);
        }
        buffer.flip();
        out.write(buffer);
    }
 
    /**
     * 将命令转换成字节数组
     * @param com
     * @return
     * @throws IOException
     * @throws Exception
     */
    private byte[] getCommandBytes(Command com) throws IOException, Exception {
        String xml = com.toXml() ;
        byte[] bytes = xml.getBytes() ;
        return bytes ;
    }
}