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;
|
|
13
|
|
14 public REPPacketSend(SocketChannel sc){
|
|
15 socketchannel = sc;
|
|
16 }
|
|
17
|
|
18 public ByteBuffer pack(REPCommand command){
|
|
19 System.out.println("send command: " + command.toString());
|
45
|
20 if(command.string == null){
|
|
21 command.setString("test");
|
|
22 }
|
0
|
23 ByteBuffer buffer = ByteBuffer.allocateDirect(24+(command.string).length()*2);
|
|
24 buffer.clear(); // position = 0
|
|
25 buffer.putInt(command.cmd); buffer.putInt(command.sid); buffer.putInt(command.eid);
|
|
26 buffer.putInt(command.seq); buffer.putInt(command.lineno);
|
|
27 buffer.putInt(command.string.length()*2);
|
|
28 for(int i=0;i<command.string.length();i++) {
|
|
29 buffer.putChar(command.string.charAt(i));
|
|
30 }
|
|
31 buffer.flip(); // limit = current position, position = 0
|
|
32 return buffer;
|
|
33 }
|
|
34
|
34
|
35 public ByteBuffer packUConv(REPCommand command){
|
44
|
36 System.out.println("send command byUTF8: " + command.toString());
|
|
37 if(command.string == null){
|
|
38 command.setString("test");
|
|
39 }
|
34
|
40 ByteBuffer buffer = ByteBuffer.allocateDirect(24+(command.string).length()*5);
|
|
41 buffer.clear(); // position = 0
|
|
42 buffer.putInt(command.cmd); buffer.putInt(command.sid); buffer.putInt(command.eid);
|
|
43 buffer.putInt(command.seq); buffer.putInt(command.lineno);
|
|
44
|
|
45 int pos = buffer.position();
|
|
46 buffer.putInt(0);
|
|
47
|
|
48 //Encode to UTF8
|
|
49 CharBuffer cb = CharBuffer.wrap(command.string);
|
|
50 Charset charset = Charset.forName("UTF-8");
|
|
51 CharsetEncoder encoder = charset.newEncoder();
|
|
52 try {
|
|
53 encoder.encode(cb, buffer, true);
|
|
54 } catch (IllegalStateException e) {
|
|
55 e.printStackTrace();
|
|
56 }
|
|
57
|
|
58 //Encoded string length set
|
|
59 buffer.putInt(pos, (buffer.position()-pos-4));
|
|
60 buffer.flip();
|
|
61
|
|
62 return buffer;
|
|
63 }
|
|
64
|
0
|
65 public void send(REPCommand command){
|
|
66 try {
|
45
|
67 socketchannel.write(pack(command));
|
0
|
68 //System.out.println(command.toString());
|
|
69 } catch (IOException e) {
|
|
70 e.printStackTrace();
|
|
71 }
|
|
72 }
|
|
73 }
|