0
|
1 package rep;
|
|
2
|
|
3 import java.io.IOException;
|
|
4 import java.nio.ByteBuffer;
|
34
|
5 import java.nio.CharBuffer;
|
0
|
6 import java.nio.channels.SocketChannel;
|
34
|
7 import java.nio.charset.Charset;
|
|
8 import java.nio.charset.CharsetEncoder;
|
|
9
|
0
|
10
|
|
11 public class REPPacketSend {
|
|
12 SocketChannel socketchannel;
|
48
|
13 // JIS/S-JIS = 2, UTF-8 = 3, UTF-?? = 5
|
50
|
14 final int CHAR_ORDER = 5;
|
48
|
15
|
0
|
16 public REPPacketSend(SocketChannel sc){
|
|
17 socketchannel = sc;
|
|
18 }
|
|
19
|
|
20 public ByteBuffer pack(REPCommand command){
|
|
21 System.out.println("send command: " + command.toString());
|
45
|
22 if(command.string == null){
|
|
23 command.setString("test");
|
|
24 }
|
0
|
25 ByteBuffer buffer = ByteBuffer.allocateDirect(24+(command.string).length()*2);
|
|
26 buffer.clear(); // position = 0
|
|
27 buffer.putInt(command.cmd); buffer.putInt(command.sid); buffer.putInt(command.eid);
|
|
28 buffer.putInt(command.seq); buffer.putInt(command.lineno);
|
|
29 buffer.putInt(command.string.length()*2);
|
|
30 for(int i=0;i<command.string.length();i++) {
|
|
31 buffer.putChar(command.string.charAt(i));
|
|
32 }
|
|
33 buffer.flip(); // limit = current position, position = 0
|
|
34 return buffer;
|
|
35 }
|
|
36
|
34
|
37 public ByteBuffer packUConv(REPCommand command){
|
44
|
38 System.out.println("send command byUTF8: " + command.toString());
|
|
39 if(command.string == null){
|
|
40 command.setString("test");
|
|
41 }
|
51
|
42 ByteBuffer buffer = ByteBuffer.allocateDirect(24+(command.string.length()*CHAR_ORDER));
|
34
|
43 buffer.clear(); // position = 0
|
|
44 buffer.putInt(command.cmd); buffer.putInt(command.sid); buffer.putInt(command.eid);
|
|
45 buffer.putInt(command.seq); buffer.putInt(command.lineno);
|
|
46
|
|
47 int pos = buffer.position();
|
|
48 buffer.putInt(0);
|
|
49
|
|
50 //Encode to UTF8
|
|
51 CharBuffer cb = CharBuffer.wrap(command.string);
|
|
52 Charset charset = Charset.forName("UTF-8");
|
|
53 CharsetEncoder encoder = charset.newEncoder();
|
|
54 try {
|
|
55 encoder.encode(cb, buffer, true);
|
|
56 } catch (IllegalStateException e) {
|
|
57 e.printStackTrace();
|
|
58 }
|
|
59
|
52
|
60 //Encoded string length set
|
51
|
61 int length = (buffer.position() -pos) -4;
|
47
|
62 System.out.println("UTF-8: Set REPComand textlen(Byte) : " + (buffer.position() - pos-4));
|
52
|
63 if(length < 0) {
|
|
64 length = 0;
|
|
65 }
|
51
|
66 buffer.putInt(pos, length);
|
|
67
|
|
68 buffer.limit(24+length);
|
|
69 buffer.rewind();
|
34
|
70
|
|
71 return buffer;
|
|
72 }
|
|
73
|
0
|
74 public void send(REPCommand command){
|
|
75 try {
|
49
|
76 socketchannel.write(pack(command));
|
|
77 //socketchannel.write(packUConv(command));
|
0
|
78 //System.out.println(command.toString());
|
|
79 } catch (IOException e) {
|
|
80 e.printStackTrace();
|
|
81 }
|
|
82 }
|
|
83 }
|