View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.testsuite.transport.socket;
17  
18  import io.netty.bootstrap.Bootstrap;
19  import io.netty.bootstrap.ServerBootstrap;
20  import io.netty.buffer.ByteBuf;
21  import io.netty.buffer.Unpooled;
22  import io.netty.channel.Channel;
23  import io.netty.channel.ChannelHandlerContext;
24  import io.netty.channel.ChannelInitializer;
25  import io.netty.channel.ChannelOption;
26  import io.netty.channel.SimpleChannelInboundHandler;
27  import io.netty.handler.codec.FixedLengthFrameDecoder;
28  import org.junit.jupiter.api.Test;
29  import org.junit.jupiter.api.TestInfo;
30  
31  import java.io.IOException;
32  import java.util.Random;
33  import java.util.concurrent.atomic.AtomicReference;
34  
35  import static org.junit.jupiter.api.Assertions.assertEquals;
36  
37  public class SocketFixedLengthEchoTest extends AbstractSocketTest {
38  
39      private static final Random random = new Random();
40      static final byte[] data = new byte[1048576];
41  
42      static {
43          random.nextBytes(data);
44      }
45  
46      @Test
47      public void testFixedLengthEcho(TestInfo testInfo) throws Throwable {
48          run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
49              @Override
50              public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
51                  testFixedLengthEcho(serverBootstrap, bootstrap);
52              }
53          });
54      }
55  
56      @Test
57      public void testFixedLengthEchoNotAutoRead(TestInfo testInfo) throws Throwable {
58          run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
59              @Override
60              public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
61                  testFixedLengthEchoNotAutoRead(serverBootstrap, bootstrap);
62              }
63          });
64      }
65  
66      public void testFixedLengthEcho(ServerBootstrap sb, Bootstrap cb) throws Throwable {
67          testFixedLengthEcho(sb, cb, true);
68      }
69  
70      public void testFixedLengthEchoNotAutoRead(ServerBootstrap sb, Bootstrap cb) throws Throwable {
71          testFixedLengthEcho(sb, cb, false);
72      }
73  
74      private static void testFixedLengthEcho(ServerBootstrap sb, Bootstrap cb, boolean autoRead) throws Throwable {
75          final EchoHandler sh = new EchoHandler(autoRead);
76          final EchoHandler ch = new EchoHandler(autoRead);
77  
78          sb.childOption(ChannelOption.AUTO_READ, autoRead);
79          sb.childHandler(new ChannelInitializer<Channel>() {
80              @Override
81              public void initChannel(Channel sch) throws Exception {
82                  sch.pipeline().addLast("decoder", new FixedLengthFrameDecoder(1024));
83                  sch.pipeline().addAfter("decoder", "handler", sh);
84              }
85          });
86  
87          cb.option(ChannelOption.AUTO_READ, autoRead);
88          cb.handler(new ChannelInitializer<Channel>() {
89              @Override
90              public void initChannel(Channel sch) throws Exception {
91                  sch.pipeline().addLast("decoder", new FixedLengthFrameDecoder(1024));
92                  sch.pipeline().addAfter("decoder", "handler", ch);
93              }
94          });
95  
96          Channel sc = sb.bind().sync().channel();
97          Channel cc = cb.connect(sc.localAddress()).sync().channel();
98          for (int i = 0; i < data.length;) {
99              int length = Math.min(random.nextInt(1024 * 3), data.length - i);
100             cc.writeAndFlush(Unpooled.wrappedBuffer(data, i, length));
101             i += length;
102         }
103 
104         while (ch.counter < data.length) {
105             if (sh.exception.get() != null) {
106                 break;
107             }
108             if (ch.exception.get() != null) {
109                 break;
110             }
111 
112             try {
113                 Thread.sleep(50);
114             } catch (InterruptedException e) {
115                 // Ignore.
116             }
117         }
118 
119         while (sh.counter < data.length) {
120             if (sh.exception.get() != null) {
121                 break;
122             }
123             if (ch.exception.get() != null) {
124                 break;
125             }
126 
127             try {
128                 Thread.sleep(50);
129             } catch (InterruptedException e) {
130                 // Ignore.
131             }
132         }
133 
134         sh.channel.close().sync();
135         ch.channel.close().sync();
136         sc.close().sync();
137 
138         if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
139             throw sh.exception.get();
140         }
141         if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
142             throw ch.exception.get();
143         }
144         if (sh.exception.get() != null) {
145             throw sh.exception.get();
146         }
147         if (ch.exception.get() != null) {
148             throw ch.exception.get();
149         }
150     }
151 
152     private static class EchoHandler extends SimpleChannelInboundHandler<ByteBuf> {
153         private final boolean autoRead;
154         volatile Channel channel;
155         final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
156         volatile int counter;
157 
158         EchoHandler(boolean autoRead) {
159             this.autoRead = autoRead;
160         }
161 
162         @Override
163         public void channelActive(ChannelHandlerContext ctx) throws Exception {
164             channel = ctx.channel();
165             if (!autoRead) {
166                 ctx.read();
167             }
168         }
169 
170         @Override
171         public void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
172             assertEquals(1024, msg.readableBytes());
173 
174             byte[] actual = new byte[msg.readableBytes()];
175             msg.getBytes(0, actual);
176 
177             int lastIdx = counter;
178             for (int i = 0; i < actual.length; i ++) {
179                 assertEquals(data[i + lastIdx], actual[i]);
180             }
181 
182             if (channel.parent() != null) {
183                 channel.write(msg.retain());
184             }
185 
186             counter += actual.length;
187         }
188 
189         @Override
190         public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
191             try {
192                 ctx.flush();
193             } finally {
194                 if (!autoRead) {
195                     ctx.read();
196                 }
197             }
198         }
199 
200         @Override
201         public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
202             if (exception.compareAndSet(null, cause)) {
203                 ctx.close();
204             }
205         }
206     }
207 }