changeset 33:1b05995d3118

add UTF-8 unpack method -> unpackUConv()
author fuchita
date Sat, 10 Nov 2007 18:13:14 +0900
parents d1c6cb6d9a2f
children 689622193437
files rep/REPPacketReceive.java
diffstat 1 files changed, 72 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/rep/REPPacketReceive.java	Sat Nov 10 17:30:14 2007 +0900
+++ b/rep/REPPacketReceive.java	Sat Nov 10 18:13:14 2007 +0900
@@ -2,8 +2,12 @@
 
 import java.io.IOException;
 import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
 import java.nio.channels.SelectionKey;
 import java.nio.channels.SocketChannel;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetDecoder;
 import java.util.LinkedList;
 import java.util.StringTokenizer;
 
@@ -24,6 +28,74 @@
 		//key.cancel();
 	}
 	
+	public REPCommand unpackUConv() {
+		ByteBuffer header = ByteBuffer.allocateDirect(HEADER_SIZE);
+		long len = 0;
+		header.clear();
+		try {
+			len = socketchannel.read(header);
+			if(len == -1){
+				if(key != null){
+					key.cancel();
+				}					
+				socketchannel.close();
+				return null;
+			}else if(len == 0){
+				return null;
+			}
+		} catch (IOException e1) {
+			e1.printStackTrace();
+		}  // limit = read length
+		if (len !=HEADER_SIZE) {
+			System.out.println("‚Ä‚·");
+			// this can't happen
+		}
+		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()/5;
+		
+		ByteBuffer textBuffer = ByteBuffer.allocateDirect(textsiz*5);
+	
+		try {
+			len = socketchannel.read(textBuffer);
+		} catch (IOException e1) {
+			e1.printStackTrace();
+		}  // limit = read length
+		if (len != textsiz * 5) {
+			// this can't happen
+			System.out.println("‚ ‚Æ");
+		}
+		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();
+		}
+		
+		String string = cb.toString();
+		
+		//System.out.println("textsize: " +textsiz);			
+		//System.out.println("CharBuffer size: " +cb.length());
+		//System.out.println(cb.toString());
+
+		REPCommand repcommand = new REPCommand(cmd, sid, eid, seqid, lineno, textsiz, string);
+		System.out.println("received command: " + repcommand.toString());
+
+		return repcommand;		
+	}
+	
+	
+	
 	public REPCommand unpack() {
 
 		ByteBuffer header = ByteBuffer.allocateDirect(HEADER_SIZE);