Looking into the Received Data
Now that we have written our first server, we need to test if it really works. The easiest way to test it is to use the telnet command. For example, you could enter telnet localhost 8080
in the command line and type something.
However, can we say that the server is working fine? We cannot really know that because it is a discard server. You will not get any response at all. To prove it is really working, let us modify the server to print what it has received.
We already know that channelRead()
method is invoked whenever data is received. Let us put some code into the channelRead()
method of the DiscardServerHandler
:
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf in = (ByteBuf) msg;
try {
while (in.isReadable()) { // (1)
System.out.print((char) in.readByte());
System.out.flush();
}
} finally {
ReferenceCountUtil.release(msg); // (2)
}
}
- This inefficient loop can actually be simplified to:
System.out.println(in.toString(io.netty.util.CharsetUtil.US_ASCII))
- Alternatively, you could do
in.release()
here.
If you run the telnet command again, you will see the server prints what has received.
The full source code of the discard server is located in the io.netty.example.discard
package of the distribution.