view rep/REPPacketReceive.java @ 170:30cf7747d134

*** empty log message ***
author pin
date Thu, 28 Aug 2008 18:56:46 +0900
parents 4ff68518e9ca
children 690182302c05
line wrap: on
line source

package rep;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;


import rep.channel.REPSocketChannel;
import rep.channel.REPUnpack;

public class REPPacketReceive implements REPUnpack<REPCommand> {
	
	REPSocketChannel<REPCommand> socketchannel;
	private final int HEADER_SIZE = 24;
	private boolean debug=false;
	
	public REPPacketReceive(REPSocketChannel<REPCommand> sc){
		socketchannel = sc;
	}
	

	public REPCommand unpackUConv(REPSocketChannel<REPCommand> sc) throws IOException {
		ByteBuffer header = ByteBuffer.allocateDirect(HEADER_SIZE);
		long len = 0;
		header.clear();
		len = socketchannel.read(header);
		if(len <= 0){
			return null;
		}
		if (len !=HEADER_SIZE) {
			throw new IOException();
		}
		header.rewind();  // position = 0

		int cmd = header.getInt();
		int sid = header.getInt();
		int eid = header.getInt();
		int seqid = header.getInt();
		int lineno = header.getInt();
		int textsiz = header.getInt();
		
		ByteBuffer textBuffer = ByteBuffer.allocateDirect(textsiz);
		
		len = socketchannel.read(textBuffer);
		if(len <= 0){
			return null;
		}
		if (len != textsiz) {
			throw new IOException();
		}
		textBuffer.rewind();

		//Decode UTF-8 to System Encoding(UTF-16) 
		Charset charset = Charset.forName("UTF-8");
		CharsetDecoder decoder = charset.newDecoder();
		CharBuffer cb = null;
		try {
			cb = decoder.decode(textBuffer);
		} catch (CharacterCodingException e) {
			e.printStackTrace();
		}
		cb.rewind();
		
		String string = cb.toString();
		
		textsiz = string.length();

		REPCommand repcommand = new REPCommand(cmd, sid, eid, seqid, lineno, textsiz, string);

		if (debug){
			System.out.println("UnPack Packet: => cmd:"+cmd+" sid:"+sid+" eid:"+eid+"seqid:"+seqid+" lineno:"+lineno+" textsiz:" +textsiz+" text: "+string);
			System.out.println("received command: " + repcommand.toString());
		}
		
		return repcommand;		
	}
}