原文地址:http://netty.io/wiki/user-guide-for-4.x.html
Writing an Echo Server
So far, we have been consuming data without responding at all. A server, however, is usually supposed to respond to a request. Let us learn how to write a response message to a client by implementing the ECHO
protocol, where any received data is sent back.
The only difference from the discard server we have implemented in the previous sections is that it sends the received data back instead of printing the received data out to the console. Therefore, it is enough again to modify the channelRead()
method:
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ctx.write(msg); // (1)
ctx.flush(); // (2)
}
- A
ChannelHandlerContext
object provides various operations that enable you to trigger various I/O events and operations. Here, we invokewrite(Object)
to write the received message in verbatim. Please note that we did not release the received message unlike we did in theDISCARD
example. It is because Netty releases it for you when it is written out to the wire. ctx.write(Object)
does not make the message written out to the wire. It is buffered internally, and then flushed out to the wire byctx.flush()
. Alternatively, you could callctx.writeAndFlush(msg)
for brevity.
If you run the telnet command again, you will see the server sends back whatever you have sent to it.
The full source code of the echo server is located in the io.netty.example.echo
package of the distribution.