view rep/REPPacketSend.java @ 115:b5062811066c

*** empty log message ***
author pin
date Sun, 23 Dec 2007 15:27:58 +0900
parents ea86e343a64b
children 628e7ffeb097
line wrap: on
line source

package rep;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;


public class REPPacketSend {
	SocketChannel socketchannel;
	// JIS/S-JIS = 2, UTF-8 = 3, UTF-?? = 5 
	final int CHAR_ORDER = 5;

	public REPPacketSend(SocketChannel sc){
		socketchannel = sc;
	}
	
	public ByteBuffer pack(REPCommand command){
    	System.out.println("send command: " + command.toString());
    	if(command.string == null){
    		command.setString("test");
    	}
    	ByteBuffer buffer = ByteBuffer.allocateDirect(24+(command.string).length()*2);
    	buffer.clear();  // position = 0 
    	buffer.putInt(command.cmd); buffer.putInt(command.sid); buffer.putInt(command.eid);
    	buffer.putInt(command.seq); buffer.putInt(command.lineno); 
    	buffer.putInt(command.string.length()*2); 
    	for(int i=0;i<command.string.length();i++) {
			buffer.putChar(command.string.charAt(i));
		}	
    	buffer.flip();    // limit = current position, position = 0
		return buffer;
	}
	
	public ByteBuffer packUConv(REPCommand command){		
    	System.out.println("send command byUTF8: " + command.toString());
    	if(command.string == null){
    		command.setString("test");
    	}
    	ByteBuffer buffer = ByteBuffer.allocateDirect(24+(command.string.length()*CHAR_ORDER));
    	buffer.clear();  // position = 0 
    	buffer.putInt(command.cmd); buffer.putInt(command.sid); buffer.putInt(command.eid);
    	buffer.putInt(command.seq); buffer.putInt(command.lineno);     	
    	
    	int pos = buffer.position();
    	buffer.putInt(0);     	
    	
    	//Encode to UTF8
    	CharBuffer cb = CharBuffer.wrap(command.string);
   		Charset charset = Charset.forName("UTF-8");
		CharsetEncoder encoder = charset.newEncoder();
		try {
			encoder.encode(cb, buffer, true);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}
		
		//Encoded string length set
		int length = (buffer.position() -pos) -4;
		System.out.println("UTF-8: Set REPComand textlen(Byte) : " + (buffer.position() - pos-4));  
		if(length < 0) {
			length = 0;
		}
		buffer.putInt(pos, length);

		buffer.limit(24+length);
		buffer.rewind();
		
		return buffer;    	
	}
	
	public void send(REPCommand command){
		try {
			//socketchannel.write(pack(command));
			socketchannel.write(packUConv(command));
			//System.out.println(command.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}