0
|
1 package rep;
|
|
2
|
|
3 import java.io.IOException;
|
|
4 import java.nio.ByteBuffer;
|
|
5 import java.nio.channels.SocketChannel;
|
|
6
|
|
7 public class REPPacketReceive {
|
|
8
|
|
9 SocketChannel socketchannel;
|
|
10 private int HEADER_SIZE = 24;
|
|
11
|
|
12 public REPPacketReceive(SocketChannel sc){
|
|
13 socketchannel = sc;
|
|
14 }
|
|
15
|
|
16
|
|
17 public REPCommand unpack() {
|
|
18
|
|
19 ByteBuffer header = ByteBuffer.allocateDirect(HEADER_SIZE);
|
|
20 long len = 0;
|
|
21 header.clear();
|
|
22 try {
|
|
23 len = socketchannel.read(header);
|
|
24 if(len == -1){
|
|
25 socketchannel.close();
|
|
26 return null;
|
|
27 }else if(len == 0){
|
|
28 return null;
|
|
29 }
|
|
30 } catch (IOException e1) {
|
|
31 e1.printStackTrace();
|
|
32 } // limit = read length
|
|
33 if (len !=HEADER_SIZE) {
|
|
34 System.out.println("‚Ä‚·");
|
|
35 // this can't happen
|
|
36 }
|
|
37 header.rewind(); // position = 0
|
|
38
|
|
39 String text = "";
|
|
40 int cmd = header.getInt();
|
|
41 int sid = header.getInt();
|
|
42 int eid = header.getInt();
|
|
43 int seqid = header.getInt();
|
|
44 int lineno = header.getInt();
|
|
45 int textsiz = header.getInt()/2;
|
|
46
|
|
47 ByteBuffer textBuffer = ByteBuffer.allocateDirect(textsiz*2);
|
|
48
|
|
49 try {
|
|
50 len = socketchannel.read(textBuffer);
|
|
51 } catch (IOException e1) {
|
|
52 e1.printStackTrace();
|
|
53 } // limit = read length
|
|
54 if (len != textsiz * 2) {
|
|
55 // this can't happen
|
|
56 System.out.println("‚ ‚Æ");
|
|
57 }
|
|
58 textBuffer.rewind();
|
|
59 for(int i=0;i<textsiz;i++) {
|
|
60 text +=textBuffer.getChar();
|
|
61 }
|
|
62 String string = text;
|
|
63 //System.out.println(string);
|
|
64 REPCommand repcommand = new REPCommand(cmd, sid, eid, seqid, lineno, textsiz, string);
|
|
65 System.out.println("received command: " + repcommand.toString());
|
|
66 return repcommand;
|
|
67 }
|
|
68 }
|