1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.echo;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.buffer.Unpooled;
20 import io.netty.channel.ChannelHandlerContext;
21 import io.netty.channel.ChannelInboundHandlerAdapter;
22
23
24
25
26
27
28 public class EchoClientHandler extends ChannelInboundHandlerAdapter {
29
30 private final ByteBuf firstMessage;
31
32
33
34
35 public EchoClientHandler() {
36 firstMessage = Unpooled.buffer(EchoClient.SIZE);
37 for (int i = 0; i < firstMessage.capacity(); i ++) {
38 firstMessage.writeByte((byte) i);
39 }
40 }
41
42 @Override
43 public void channelActive(ChannelHandlerContext ctx) {
44 ctx.writeAndFlush(firstMessage);
45 }
46
47 @Override
48 public void channelRead(ChannelHandlerContext ctx, Object msg) {
49 ctx.write(msg);
50 }
51
52 @Override
53 public void channelReadComplete(ChannelHandlerContext ctx) {
54 ctx.flush();
55 }
56
57 @Override
58 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
59
60 cause.printStackTrace();
61 ctx.close();
62 }
63 }