Reputation: 949
public class TCPNetty {
static class Handler extends SimpleChannelUpstreamHandler {
private static final char[] hexCode = "0123456789ABCDEF".toCharArray();
public String printHexBinary(byte[] data) {
StringBuilder r = new StringBuilder(data.length * 2);
for (byte b: data) {
r.append(hexCode[(b >> 4) & 0xF]);
r.append(hexCode[(b & 0xF)]);
}
return r.toString();
}@
Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
String msg = (String) e.getMessage();
String mainstr = "";
mainstr = printHexBinary(msg.getBytes()).toUpperCase();
System.out.println("========================" + mainstr);
System.out.println("@@@@@@@@@@@@@@@@@@@@" + mainstr);
ctx.sendUpstream(e);
}@
Override@ SuppressWarnings({
"ThrowableResultOfMethodCallIgnored"
})
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
e.getChannel().close();
}
}
public static void main(String[] args) {
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
final ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast("handler", new Handler());
// pipeline.addLast("executor", executionHandler);
// pipeline.addLast("handler", new EchoCloseServerHandler());
return pipeline;
}
});
bootstrap.bind(new InetSocketAddress(5002));
}
}
problem is that when i received hex string its showing different output in linux and windows
for example : in Windows getting : 2929B10007003F972D30BD0D in Linux getting : 2929EFBFBD000700EFBFBDEFBFBD2D30EFBFBD0D
i think issue with netty string decoder but not sure .
Upvotes: 1
Views: 143
Reputation:
StringEncoder and StringDecoder use the default Charset unless otherwise specified. The default charset on Linux is (probably) UTF-8, whereas on windows it's typically cp-1251. This means the encoded forms will differ, as you are seeing.
To fix this, change your pipeline code to:
pipeline.addLast("decoder", new StringDecoder(StandardCharsets.UTF_8));
pipeline.addLast("encoder", new StringEncoder(StandardCharsets.UTF_8));
and
mainstr = printHexBinary(msg.getBytes()).toUpperCase();
to
mainstr = printHexBinary(msg.getBytes(StandardCharsets.UTF_8)).toUpperCase();
StandardCharsets requires Java 1.7.
Any other Charset that can represent all of your input would also suffice, but UTF-8 is typical, so you should probably stick with that.
Upvotes: 2