Netty 4.0 - StringDecoder and ChannelInboundMessageHandlerAdapter<String> not working - java

I'm using netty 4.0.0-CR3, following the example on server-side:
https://github.com/netty/netty/blob/master/example/src/main/java/io/netty/example/telnet/TelnetServerPipelineFactory.java
I've constructed my pipeline as follows:
private static final StringDecoder DECODER = new StringDecoder(CharsetUtil.UTF_8);
#Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("decoder", DECODER);
// and then business logic
pipeline.addLast("serverHandler", new ServerHandler());
}
And handler:
public class ServerHandler extends ChannelInboundMessageHandlerAdapter<String> {
private static final Logger LOGGER = LoggerFactory.getLogger(ServerHandler.class);
public void messageReceived(ChannelHandlerContext ctx, String request)
throws Exception {
// Displays the message
LOGGER.info("Received: " + request);
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
LOGGER.error("Unexpected exception from downstream.", cause);
ctx.close();
}
}
I created a simple C# client that encodes String into bytes, and send to the server. However, I don't see EITHER StringDecoder's decode() OR handler's messageReceived() called.
I then removed StringDecoder() in pipeline, and changed the handler to be:
public class Handler extends ChannelInboundByteHandlerAdapter {
#Override
protected void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in)
throws Exception {
System.out.println("called " + in.toString(CharsetUtil.UTF_8));
}
}
Now it works properly. Functionally both pipelines should work right? Why is the first setup not working? The client code is the same.
Thanks a lot!

The documentation for StringDecoder clearly states that it must be used in conjunction with a ByteToMessageDecoder if used over a stream connection (such as TCP). The example you refer to has such a handler in front of the StringDecoder.

Thanks guys! so I added the following:
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.nulDelimiter()));
And this still didn't work until I explicitly add '\0' to the end to String in C# :
ASCIIEncoding encoder = new ASCIIEncoding();
int index = random.Next(0, 2);
byte[] buffer = encoder.GetBytes(list[index] + "\0");
The weird thing is that, I was using Netty 3.6 previously, and everything worked fine even without a FrameDecoder (only StringDecoder was there / client code was same) but now I have to do the steps above to make it to work..........?

Related

Netty getting An exceptionCaught() event was fired, and it reached at the tail of the pipeline on TextWebsocketEncoder

I try to do simple web socket decode and then encode but I'm getting this exception when it pass the TextWebsocketDecoder handler:
io.netty.channel.DefaultChannelPipeline$TailContext exceptionCaught
WARNING: An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.
io.netty.util.IllegalReferenceCountException: refCnt: 0, decrement: 1
at io.netty.buffer.AbstractReferenceCountedByteBuf.release(AbstractReferenceCountedByteBuf.java:101)
at io.netty.buffer.DefaultByteBufHolder.release(DefaultByteBufHolder.java:73)
at io.netty.util.ReferenceCountUtil.release(ReferenceCountUtil.java:59)
at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:112)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:318)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:304)
at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:103)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:318)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:304)
at io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler$1.channelRead(WebSocketServerProtocolHandler.java:147)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:318)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:304)
at io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:318)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:304)
at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:276)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:263)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:318)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:304)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:846)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354)
at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:112)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137)
at java.lang.Thread.run(Thread.java:745)
What I have is simple Initializer which work find until TextWebsocketEncoder:
public class ServerInitializer extends ChannelInitializer<Channel> {
private final ChannelGroup group;
public GameServerInitializer(ChannelGroup group) {
this.group = group;
}
#Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(64 * 1024));
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpRequestHandler("/ws"));
pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
pipeline.addLast(new TextWebSocketFrameHandler(group));
pipeline.addLast("textWebsocketDecoder",new TextWebsocketDecoder());
pipeline.addLast("textWebsocketEncoder",new TextWebsocketEncoder());
}
}
TextWebSocketFrameHandler
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>{
private final ChannelGroup group;
public TextWebSocketFrameHandler(ChannelGroup group) {
this.group = group;
}
#Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
ctx.pipeline().remove(HttpRequestHandler.class);
group.writeAndFlush(new TextWebSocketFrame("Client " + ctx.channel() + " joined"));
group.add(ctx.channel());
} else {
super.userEventTriggered(ctx, evt);
}
}
#Override
public void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
ctx.fireChannelRead(msg);
//group.writeAndFlush(msg.retain());
}
}
and this are the TextWebsocketDecoder and TextWebsocketEncoder :
TextWebsocketDecoder :
public class TextWebsocketDecoder extends MessageToMessageDecoder<TextWebSocketFrame>
{
#Override
protected void decode(ChannelHandlerContext ctx, TextWebSocketFrame frame, List<Object> out) throws Exception
{
String json = frame.text();
JSONObject jsonObject = new JSONObject(json);
int type = jsonObject.getInt("type");
JSONArray msgJsonArray = jsonObject.getJSONArray("msg");
String user = msgJsonArray.getString(0);
String pass = msgJsonArray.getString(1);
String connectionkey = msgJsonArray.getString(2);
int timestamp = jsonObject.getInt("timestamp");
JSONObject responseJson = new JSONObject();
responseJson.put("type",Config.LOGIN_SUCCESS);
responseJson.put("connectionkey",connectionkey);
out.add(responseJson); // After This im getting the exception !!!
}
}
TextWebsocketEncoder
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
public class TextWebsocketEncoder extends MessageToMessageEncoder<JSONObject>
{
#Override
protected void encode(ChannelHandlerContext arg0, JSONObject arg1, List<Object> out) throws Exception {
String json = arg1.toString();
out.add(new TextWebSocketFrame(json));
}
}
The exception
Inside your TextWebSocketFrameHandler, you are calling ctx.fireChannelRead(msg);, this passes the message up 1 chain, however MessageToMessageDecoder isn't prepared to deal with this. To explain this problem I need to explain how the MessageToMessageDecoder works.
MessageToMessageDecoder works by catching every message from the upstream and passing them to your custom code, your custom code handles the work, and the mtmd handles the closing of the resource you passed in.
Since you are passing the reference to the other side, you are effectively closing the WebSocketFrame multiple times, causing bugs. MessageToMessageDecoder even warns you for this in the javadoc.
To solve the problem, we follow the instruction in the manual and make our channelRead the following:
#Override
public void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
msg.retain(); // ferrybig: fixed bug http://stackoverflow.com/q/34634750/1542723
ctx.fireChannelRead(msg);
//group.writeAndFlush(msg.retain());
}
The not sending back problem
Inside your comments, you stated the code doesn't send anything back. This is expected as your pipeline only consumes data and passes it up the chain. To fix this, it would require some rework at your pipeline.
We need to swap the order of the json-webframe decoder and encoder:
pipeline.addLast("textWebsocketDecoder",new TextWebsocketEncoder());
pipeline.addLast("textWebsocketEncoder",new TextWebsocketDecoder());
This is because your Decoder is generating the output that would be send back ↑ the chain of handlers, this output won't be seen by the encoder if the decoder was above that. (Your decoder shouldn't be called a decoder following the netty naming)
We need to change your decoder to send the generated data actually back ↑ the chain instead of ↓ into the non-existing void.
To make these changes, we going to let the TextWebSocketDecoder extend ChannelInboundHandlerAdapter instead of MessageToMessageDecoder<TextWebSocketFrame> since we are handling messages instead of passing them to a other handler.
We are changing the signature of the decode method to channelRead(ChannelHandlerContext ctx, Object msg), and add some boilerplate code:
public void channelRead(ChannelHandlerContext ctx, Object msg) /* throws Exception */
TextWebSocketFrame frame = (TextWebSocketFrame) msg;
try {
/* Remaining code, follow the steps further of see end result */
} finally {
frame.release();
}
}
We adapt our code to pass the result up the pipeline instead of down:
public void channelRead(ChannelHandlerContext ctx, Object msg) /* throws Exception */
TextWebSocketFrame frame = (TextWebSocketFrame) msg;
try {
String json = frame.text();
JSONObject jsonObject = new JSONObject(json);
int type = jsonObject.getInt("type");
JSONArray msgJsonArray = jsonObject.getJSONArray("msg");
String user = msgJsonArray.getString(0);
String pass = msgJsonArray.getString(1);
String connectionkey = msgJsonArray.getString(2);
int timestamp = jsonObject.getInt("timestamp");
JSONObject responseJson = new JSONObject();
responseJson.put("type",Config.LOGIN_SUCCESS);
responseJson.put("connectionkey",connectionkey);
ctx.writeAndFlush(responseJson)
} finally {
frame.release();
}
}
Notice that you may be tempted to remove our previous code from the exception, but doing this will trigger undefined behavior when ran under the async nature of netty.
You use SimpleChannelInboundHandler which auto-releases catched data according to documentation.
So, when you call ctx.fireChannelRead(msg); to pass msg to others handlers on pipeline, there is a problem besauce msg will be released.
To fix this, you can use ChannelInboundHandlerAdapter or you can stop auto-releasing process of SimpleChannelInboundHandler by calling the proper constructor, or you can call ReferenceCountUtil.retain(msg); before firing upper on pipeline.
See documentation of SimpleChannelInboundHandler here:
http://netty.io/4.0/api/io/netty/channel/SimpleChannelInboundHandler.html
and read about Reference counted objects here (new concept of netty 4):
http://netty.io/wiki/reference-counted-objects.html

Netty 4 read/write in handler multiple times

I'm new in Netty, and I decided to start with 4.0.0, because I thought it should be better, because it's newer. My server application should receive data from gps devices, and the process is like this - at first I'm receiving 2 bytes, which are length of device imei, and then I'm receiving imei with that length, then I should send 0x01 to device if I want to accept data from it. After my answer device sends me gps data with AVL protocol. Now my server is working without Netty, and I want to change it to work with netty.
This is what I have done:
I have created server class like this
public class BusDataReceiverServer {
private final int port;
private final Logger LOG = LoggerFactory.getLogger(BusDataReceiverServer.class);
public BusDataReceiverServer(int port) {
this.port = port;
}
public void run() throws Exception {
LOG.info("running thread");
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try{
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new BusDataReceiverInitializer());
b.bind(port).sync().channel().closeFuture().sync();
}catch (Exception ex){
LOG.info(ex.getMessage());
}
finally {
LOG.info("thread closed");
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
new BusDataReceiverServer(3129).run();
}
}
and created initializer class
public class BusDataReceiverInitializer extends ChannelInitializer<SocketChannel> {
#Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast("imeiDecoder", new ImeiDecoder());
pipeline.addLast("busDataDecoder", new BusDataDecoder());
pipeline.addLast("encoder", new ResponceEncoder());
pipeline.addLast("imeiHandler", new ImeiReceiverServerHandler());
pipeline.addLast("busDataHandler", new BusDataReceiverServerHandler());
}
}
then I have created decoders and encoder and 2 handlers. My imeiDecoder and encoder, and ImeiReceiverServerHandler are working. This is my ImeiReceiverServerHandler
public class ImeiReceiverServerHandler extends ChannelInboundHandlerAdapter {
private final Logger LOG = LoggerFactory.getLogger(ImeiReceiverServerHandler.class);
#Override
public void messageReceived(ChannelHandlerContext ctx, MessageList<Object> msgs) throws Exception {
MessageList<String> imeis = msgs.cast();
String imei = imeis.get(0);
ctx.write(Constants.BUS_DATA_ACCEPT);
ctx.fireMessageReceived(msgs);
}
#Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx); //To change body of overridden methods use File | Settings | File Templates.
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause); //To change body of overridden methods use File | Settings | File Templates.
}
}
Now, after accepting I don't understand how to continue receive gps data and forward it to handler BusDataReceiverServerHandler.
If anyone could help me with this or could offer me useful documentation, I will be very grateful. Or if it is possible to do this with Netty 3, for this I will also be thankful.
I have not used Netty 4, so I am not sure if my answer will be 100% accurate or the best way to do things in Netty 4, but what you need to do is track the state of your connection / client session in order to know when to forward messages to your second handler.
E.g.
private enum HandlerState { INITIAL, IMEI_RECEIVED; }
private HandlerState state = HandlerState.INITIAL;
#Override
public void messageReceived(ChannelHandlerContext ctx, MessageList<Object> msgs) throws Exception
{
if (state == HandlerState.INITIAL)
{
MessageList<String> imeis = msgs.cast();
String imei = imeis.get(0);
ctx.write(Constants.BUS_DATA_ACCEPT);
state = HandlerState.IMEI_RECEIVED;
} else
{
// Forward message to next handler...
// Not sure exactly how this is done in Netty 4
// Maybe: ctx.fireMessageReceived(msgs);
// Or maybe it is:
// ctx.nextInboundMessageBuffer().add(msg);
// ctx.fireInboundBufferUpdated();
// I believe you could also remove the IMEI handler from the
// pipeline instead of having it keep state, if it is not going to do anything
// further.
}
}
So either track state in the handler, or remove the handler from the pipeline once it has finished if it will not be used further. When tracking state, you can either keep the state in the handler itself (as shown above), or keep the state variables in the context / attribute map (however that is done in netty 4).
The reason to not keep the state in the handler itself would be if you were going to make the handler shareable (one instance used across multiple channels). It is not necessary to do this, but there could be some resource savings if you have a large number of concurrent channels.

Netty 4 - Encoder not writing to following encoder

I currently have set up a networked client that makes use of two encoders, a single decoder, and a ChannelInboundMessageHandlerAdapter<ByteBuf>. The encoders are a MessageToByteEncoder<Packet> and a ByteToByteEncoder. I've tried using a ChannelOutboundMessageHandlerAdapter and a ChannelOutboundByteHandlerAdapter but neither of them remedied the problem. It enters the first encoder (PacketEncoder or the MessageToByteEncoder<Packet>) just fine, but fails to enter the ByteToByteEncoder afterword and no data is sent to the server.
My pipeline is set up like so:
ChannelPipeline pipeline = ch.pipeline();
// Decoders
pipeline.addLast("buffer_length_decoder", new BufferLengthDecoder());
pipeline.addLast("packet_decoder", new PacketDecoder());
// Encoder
pipeline.addLast("buffer_length_encoder", new BufferLengthEncoder());
pipeline.addLast("packet_encoder", new PacketEncoder());
PacketEncoder looks like so:
public class PacketEncoder extends MessageToByteEncoder<Packet> {
private static final Logger logger = LoggerFactory.getLogger(PacketEncoder.class);
#Override
protected void encode(ChannelHandlerContext ctx, Packet msg, ByteBuf out) throws Exception {
ByteBuf buf = msg.buf();
buf = buf.capacity(buf.readableBytes());
logger.info(Utils.toHexString(buf.array()));
out.writeBytes(buf);
}
}
BufferLengthEncoder looks like so:
public class BufferLengthEncoder extends ByteToByteEncoder {
private static final Logger logger = LoggerFactory.getLogger(BufferLengthEncoder.class);
#Override
protected void encode(ChannelHandlerContext ctx, ByteBuf in, ByteBuf out) throws Exception {
logger.info(Utils.toHexString(in.array()));
out = out.writeInt(in.readableBytes()).writeBytes(in);
}
}
I have tried changing their order in the pipeline to no avail. I assume that I'm just missing something nonsensical somewhere, but I'm unsure where or what. Any and all help is much appreciated.
Thanks in advance!
Sounds strange to me... could you please write a unit test that shows the problem and open an issue after you are sure it is a bug ?
https://github.com/netty/netty/issues

How to pass application/user data to the ChannelHandler Netty

When you design an a client that is going to connect to a lot of servers, like a crawler.
You will code something like that :
// the pipeline
public class CrawlerPipelineFactory implements ChannelPipelineFactory {
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(new CrawlerHandler());
}
}
// the channel handler
public class CrawlerHandler extends SimpleChannelHandler {
#Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
// ...
}
}
// the main :
public static void main(){
ChannelFactory factory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool());
ClientBootstrap scannerBootstrap = new ClientBootstrap(factory);
scannerBootstrap.setPipelineFactory(new CrawlerPipelineFactory());
while(true){
MyURL url = stack.pop();
ChannelFuture connect = scannerBootstrap.connect(url.getSocketAddress());
}
}
Now when you are in your ApplicationHandler, the stuff that implements your SimpleChannelHandler or WhatEverStreamHandler, (CrawlerHander in the example) the only piece of information you get is the socketAdress you are connecting to that you can recover in "public void channelConnected()" function.
Ok but what if I want to recover some user data, like the MyURL object you see in my code example ?
I use a dirty hack, I use a Map<"ip:port",MyURL> so I can retrieve the associated data in channelConnected because I know ip:port i'm connected on.
This hack is really dirty, it won't work if you are connecting simultaneously to the same server (or you'll have to bind to a local port and use a key like "localport:ip:remoteport" but it's so dirty).
So I'm seeking what is the good way to pass data the the CrawlerHander ?
It would be cool if we could pass this data via the connect() method of the bootstrap. I know I can pass argument in my ChannelPipelineFactory.getPipeline() because it's invoked via connect(). But now we can't, so here is another dirty hack I use :
EDIT:
// the main
while(!targets.isEmpty()){
client.connect("localhost",111); // we will never connect to localhost, it's a hack
}
// the pipleline
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(
new CrawlerHandler(targets.pop()) // I specify each new host to connect here
);
}
// in my channel handler
// Now I have the data I want in the constructor, so I m sure I get them before everything is called
public class CrawlerHandler extends SimpleChannelHandler {
ExtraParameter target;
public CrawlerHandler(ExtraParameter target) {
this.target = target;
// but, and it's the most dirty part, I have to abort the connection to localhost, and reinit a new connection to the real target
boolean bFirstConnect=true;
#Override
public void connectRequested(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
if(bFirstConnect){
bFirstConnect = false;
ctx.getChannel().connect(target.getSocketAddr());
}
You can pass variables to Channel via Bootstrap.
Netty.io 4.1 & SO - Adding an attribute to a Channel before creation
Update to this answer while very late.
You can pass the data to the newly connected channel/channel handler using ChannelLocal or in ChannelHandlerContext (or in the Channel it self in latest Netty 3.x) using a connect future listener. In below example, ChannelLocal is used.
public class ChannelDataHolder {
public final static ChannelLocal<String> CHANNEL_URL = new ChannelLocal<String>(true);
}
// for each url in bootstrap
MyURL url = ....;
ChannelFuture cf = scannerBootstrap.connect(url.getSocketAddress());
final String urlString = url.getUrl();
cf.addListener(new ChannelFutureListener() {
#Override
public void operationComplete(ChannelFuture future) throws Exception {
ChannelDataHolder.CHANNEL_URL.set(future.getChannel(), urlString);
}
});
//In the handler
public class CrawlerHandler extends SimpleChannelHandler {
#Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
String urlString = ChannelDataHolder.CHANNEL_URL.get(ctx.getChannel());
// ...use the data here
}
}
Note: instead of ChannelLocal, you can set and get the data using
ChannelHandlerContext.setAttachment()/getAttachment()
Channel.setAttachment()/getAttachment() in latest 3.x version of Netty
but both approaches does not support type safety.

Netty Camel samples

I'm a newbie to Netty.
I'm looking for some samples. (Preferably but not necessarity using Camel Netty Component and Spring)
Specifically a sample Netty app that consumes TCP messages.
Also how can I write a JUnit test that can test this netty app?
Thanks,
Dar
I assume you still want to integrate with Camel. I would first look at the camel documentation . After that frustrates you, you will need to start experimenting. I have one example where I created a Camel Processor as a Netty Server. The Netty components work such that a From endpoint is a server which consumes and a To endpoint is a client which produces. I needed a To endpoint that was a server and the component did not support that. I simply implemented a Camel Processor as a spring bean that started a Netty Server when it was initialized. The JBoss Netty documentation and samples are very good though. It is worthwhile to step through them.
Here is my slimmed down example. It is a server that sends a message to all the clients that are connected. If you are new to Netty I highly suggest going through the samples I linked to above:
public class NettyServer implements Processor {
private final ChannelGroup channelGroup = new DefaultChannelGroup();
private NioServerSocketChannelFactory serverSocketChannelFactory = null;
private final ExecutorService executor = Executors.newCachedThreadPool();
private String listenAddress = "0.0.0.0"; // overridden by spring-osgi value
private int listenPort = 51501; // overridden by spring-osgi value
#Override
public void process(Exchange exchange) throws Exception {
byte[] bytes = (byte[]) exchange.getIn().getBody();
// send over the wire
sendMessage(bytes);
}
public synchronized void sendMessage(byte[] message) {
ChannelBuffer cb = ChannelBuffers.copiedBuffer(message);
//writes to all clients connected.
this.channelGroup.write(cb);
}
private class NettyServerHandler extends SimpleChannelUpstreamHandler {
#Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelOpen(ctx, e);
//add client to the group.
NettyServer.this.channelGroup.add(e.getChannel());
}
// Perform an automatic recon.
#Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
super.channelConnected(ctx, e);
// do something here when a clien connects.
}
#Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
// Do something when a message is received...
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
// Log the exception/
}
}
private class PublishSocketServerPipelineFactory implements ChannelPipelineFactory {
#Override
public ChannelPipeline getPipeline() throws Exception {
// need to set the handler.
return Channels.pipeline(new NettyServerHandler());
}
}
// called by spring to start the server
public void init() {
try {
this.serverSocketChannelFactory = new NioServerSocketChannelFactory(this.executor, this.executor);
final ServerBootstrap serverBootstrap = new ServerBootstrap(this.serverSocketChannelFactory);
serverBootstrap.setPipelineFactory(new PublishSocketServerPipelineFactory());
serverBootstrap.setOption("reuseAddress", true);
final InetSocketAddress listenSocketAddress = new InetSocketAddress(this.listenAddress, this.listenPort);
this.channelGroup.add(serverBootstrap.bind(listenSocketAddress));
} catch (Exception e) {
}
}
// called by spring to shut down the server.
public void destroy() {
try {
this.channelGroup.close();
this.serverSocketChannelFactory.releaseExternalResources();
this.executor.shutdown();
} catch (Exception e) {
}
}
// injected by spring
public void setListenAddress(String listenAddress) {
this.listenAddress = listenAddress;
}
// injected by spring
public void setListenPort(int listenPort) {
this.listenPort = listenPort;
}
}
The camel release has a lot of examples but without a simple one for netty component.
Netty component can be use to setup a socket server to consume message and produce response back to the client. After some time of search on the web, I create my own tutorial using netty component in camel as a simple Camel-Netty hello world example to show:
Using netty component in camel to receive TCP message
Using POJO class to process the received message and create response
Sending response back to client.

Categories

Resources