Mercurial > hg > RemoteEditor > REPSessionManager
view rep/REPPacketReceive.java @ 137:1ea856259add
*** empty log message ***
author | pin |
---|---|
date | Wed, 27 Aug 2008 18:43:09 +0900 |
parents | 0bd4ffc33bdb |
children | 4ff68518e9ca |
line wrap: on
line source
package rep; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.SelectableChannel; 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; import rep.channel.ChannelSimulator; import rep.channel.REPSocketChannel; public class REPPacketReceive { REPSocketChannel<REPCommand> socketchannel; private final int HEADER_SIZE = 24; SelectionKey key; public REPPacketReceive(REPSocketChannel<REPCommand> sc){ socketchannel = sc; } public void setkey(SelectionKey key) { this.key = key; } 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("error."); // 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(); ByteBuffer textBuffer = ByteBuffer.allocateDirect(textsiz); try { len = socketchannel.read(textBuffer); if(len == -1){ if(key != null){ key.cancel(); } socketchannel.close(); return null; } } catch (IOException e1) { e1.printStackTrace(); } // limit = read length if (len != textsiz) { // this can't happen System.out.println("error."); } 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); 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; } }