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