view src/sample/pack/PackTest.java @ 8:bf97ccde466d

*** empty log message ***
author fuchita
date Sun, 22 Oct 2006 19:06:59 +0900
parents db9137964f03
children
line wrap: on
line source

package sample.pack;


import java.nio.*;

public class PackTest {

    static int cmd = 47;
    static  int eid = 1;
    static  int lineno = 100;
    static  int sid = 1;
    static  int seqid = 32767;
    static  int textsiz = 5;
    
    /*private static int cmd2;
    private static int eid2;
    private static int lineno2;
    private static int sid2;
    private static int seqid2;
    private static int textsiz2;
   */
   
    static byte[] chgBytes( int i ){
    	byte[] b = new byte[4] ;
        
    	b[0] = (byte)((i >>> 24 ) & 0xFF);
    	b[1] = (byte)((i >>> 16 ) & 0xFF);
    	b[2] = (byte)((i >>>  8 ) & 0xFF);
    	b[3] = (byte)((i >>>  0 ) & 0xFF);
        
    	return b;
    }

    public static ByteBuffer pack(ByteBuffer buffer,int cmd, int sid, int eid, int seqid, int lineno, String text ) {	


    	//System.out.println("pack:" + cmd +", "+ sid +", "+ eid +", "+ seqid +", "+ lineno);
    
    	//ByteBuffer buffer = ByteBuffer.allocateDirect(24+textsiz);
    	
    	buffer.putInt(cmd); buffer.putInt(sid); buffer.putInt(eid);
    	buffer.putInt(seqid); buffer.putInt(lineno); 
    	buffer.putInt(text.length()); 
    	//buffer.putString(text);
    	
    	for(int i=0;i<text.length();i++) {
			buffer.putChar(text.charAt(i));
		}	
    	System.out.println("pack:" + cmd +", "+ sid +", "+ eid +", "+ seqid +", "+ lineno);
    	
    	return buffer;
    }

    public static void unpack(ByteBuffer buffer) {
    	int cmd,  sid,  eid,  seqid,  lineno; String text = "";
    	int textsiz = 0;

    	buffer.rewind();
    	
    	cmd = buffer.getInt(); sid = buffer.getInt(); eid = buffer.getInt();
    	seqid = buffer.getInt(); lineno = buffer.getInt(); textsiz = buffer.getInt();
    	

    	for(int i=0;i<textsiz;i++) {
			text +=buffer.getChar();
		}

    	System.out.println("unpack:" + cmd +", "+ sid +", "+ eid +", "+ seqid +", "+ lineno +"," + text);
    	//byte[] readbyte = new byte[textsiz];
    	//for(int i = 0; i < textsiz; i++){
			//readbyte[i] = buffer.get();
			//System.out.println(readbyte[i]);
		//}
    	//text = new String(readbyte, 0, textsiz);
    	
    }
    
    public static void main(String args[]) {
    	ByteBuffer testbuf = ByteBuffer.allocateDirect(1024);

    	System.out.println("pack unpack test.");
    	pack(testbuf, cmd, sid, eid, seqid, lineno, "test");

    	//System.out.println("check:" + testbuf.get(0)+ ":" +testbuf.get(1)+ ":" +testbuf.get(2)+ ":" +testbuf.get(3));
    	//System.out.println("check:" + testbuf.get(4)+ ":" +testbuf.get(5)+ ":" +testbuf.get(6)+ ":" +testbuf.get(7));

    	//String string = "";
    	unpack(testbuf);

    	//System.out.println("unpack:" + cmd2 +", "+ sid2 +", "+ eid2 +", "+ seqid2 +", "+ lineno2 +", "+ string);
    }
}