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