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