Mercurial > hg > RemoteEditor > REPSessionManager
view rep/REPPacketSend.java @ 36:ec1cd5d388f3
UTF-8 TEST
author | fuchita |
---|---|
date | Sat, 10 Nov 2007 18:36:58 +0900 |
parents | eb02fde61a69 |
children | 618d76c06b9e |
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; public REPPacketSend(SocketChannel sc){ socketchannel = sc; } public ByteBuffer pack(REPCommand command){ System.out.println("send command: " + command.toString()); 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()); ByteBuffer buffer = ByteBuffer.allocateDirect(24+(command.string).length()*5); 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 buffer.putInt(pos, (buffer.position()-pos-4)); buffer.flip(); return buffer; } public void send(REPCommand command){ try { socketchannel.write(pack(command)); //System.out.println(command.toString()); } catch (IOException e) { e.printStackTrace(); } } }