1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.testsuite.transport.socket;
17
18 import io.netty.bootstrap.ServerBootstrap;
19 import io.netty.channel.Channel;
20 import io.netty.channel.ChannelHandler;
21 import io.netty.channel.ChannelHandlerContext;
22 import io.netty.channel.ChannelInboundHandlerAdapter;
23 import io.netty.channel.ChannelOption;
24 import io.netty.util.internal.SocketUtils;
25 import org.junit.jupiter.api.Disabled;
26 import org.junit.jupiter.api.Test;
27 import org.junit.jupiter.api.TestInfo;
28
29 import java.net.Socket;
30 import java.util.ArrayList;
31 import java.util.List;
32 import java.util.concurrent.CountDownLatch;
33
34 import static org.junit.jupiter.api.Assertions.assertTrue;
35
36 public class ServerSocketSuspendTest extends AbstractServerSocketTest {
37
38 private static final int NUM_CHANNELS = 10;
39 private static final long TIMEOUT = 3000000000L;
40
41 @Test
42 @Disabled("Need to investigate why it fails on osx")
43 public void testSuspendAndResumeAccept(TestInfo testInfo) throws Throwable {
44 run(testInfo, new Runner<ServerBootstrap>() {
45 @Override
46 public void run(ServerBootstrap serverBootstrap) throws Throwable {
47 testSuspendAndResumeAccept(serverBootstrap);
48 }
49 });
50 }
51
52 public void testSuspendAndResumeAccept(ServerBootstrap sb) throws Throwable {
53 AcceptedChannelCounter counter = new AcceptedChannelCounter(NUM_CHANNELS);
54
55 sb.option(ChannelOption.SO_BACKLOG, 1);
56 sb.option(ChannelOption.AUTO_READ, false);
57 sb.childHandler(counter);
58
59 Channel sc = sb.bind().sync().channel();
60
61 List<Socket> sockets = new ArrayList<Socket>();
62
63 try {
64 long startTime = System.nanoTime();
65 for (int i = 0; i < NUM_CHANNELS; i ++) {
66 Socket s = new Socket();
67 SocketUtils.connect(s, sc.localAddress(), 10000);
68 sockets.add(s);
69 }
70
71 sc.config().setAutoRead(true);
72
73 counter.latch.await();
74
75 long endTime = System.nanoTime();
76 assertTrue(endTime - startTime > TIMEOUT);
77 } finally {
78 for (Socket s: sockets) {
79 s.close();
80 }
81 }
82
83 Thread.sleep(TIMEOUT / 1000000);
84
85 try {
86 long startTime = System.nanoTime();
87 for (int i = 0; i < NUM_CHANNELS; i ++) {
88 Socket s = new Socket();
89 s.connect(sc.localAddress(), 10000);
90 sockets.add(s);
91 }
92 long endTime = System.nanoTime();
93
94 assertTrue(endTime - startTime < TIMEOUT);
95 } finally {
96 for (Socket s: sockets) {
97 s.close();
98 }
99 }
100 }
101
102 @ChannelHandler.Sharable
103 private static final class AcceptedChannelCounter extends ChannelInboundHandlerAdapter {
104
105 final CountDownLatch latch;
106
107 AcceptedChannelCounter(int nChannels) {
108 latch = new CountDownLatch(nChannels);
109 }
110
111 @Override
112 public void channelActive(ChannelHandlerContext ctx) throws Exception {
113 latch.countDown();
114 }
115 }
116 }