Mercurial > hg > RemoteEditor > REPSessionManager
view rep/REPPacketSend.java @ 48:b4991de8e83a
UTF-8 Pack Method packUConv()/unpackUConv() add
author | fuchita |
---|---|
date | Tue, 13 Nov 2007 18:53:24 +0900 |
parents | f4eb7fd098c4 |
children | f8b4101746d2 |
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 = 3; 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(); } System.out.println("UTF-8: Set REPComand textlen(Byte) : " + (buffer.position() - pos-4)); //Encoded string length set buffer.putInt(pos, (buffer.position()-pos-4)); buffer.flip(); return buffer; } public void send(REPCommand command){ try { socketchannel.write(packUConv(command)); //System.out.println(command.toString()); } catch (IOException e) { e.printStackTrace(); } } }