views:

44

answers:

1

Just started playing around with netty in implementing my own server. Took me a while to get the hang of it but now I was able to accept clients by writing my own MessageHandler and inside messageReceived I was able to read from the buffer and did some business logic related to the data received.

However the question now is, how do I write data into connected clients? I saw the sample code where you can write to the channel in the event of a new message like this:

public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
    Channel ch = e.getChannel();
    ch.write(e.getMessage());
}

but what if you don't want to write the data back at that point? What if the client stays connected in the socket and waits until some event occurs in the server? In that case how will my server find the right socket to write to? Am I suppose to keep a reference to the channel object? Is this the convention?

I looked further into the code and saw a method called writeRequested. Is that related? Who calls that? And is it needed?

+1  A: 

As long as you have the reference to the Channel (or ChannelHandlerContext), you can call Channel.write() (or Channels.write()) from anywhere, any thread.

writeRequested() is called when you trigger the writeRequested event by calling Channel.write() or calling ChannelHandlerContext.sendDownstream(MessageEvent).

Trustin Lee