1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.transport.nio;
21
22 import static org.junit.Assert.*;
23
24 import java.io.IOException;
25 import java.net.InetSocketAddress;
26 import java.net.Socket;
27 import java.util.concurrent.CountDownLatch;
28 import java.util.concurrent.TimeUnit;
29
30 import org.apache.mina.api.AbstractIoFilter;
31 import org.apache.mina.api.IdleStatus;
32 import org.apache.mina.api.IoSession;
33 import org.apache.mina.transport.nio.NioTcpServer;
34 import org.junit.BeforeClass;
35 import org.junit.Test;
36
37
38
39
40
41
42 public class IdleTcpServerTest {
43
44 private static final int CLIENT_COUNT = 3;
45
46 @BeforeClass
47 public static void setup() {
48
49 }
50
51 @Test
52 public void readIdleTest() throws IOException {
53 final NioTcpServer server = new NioTcpServer();
54
55 final CountDownLatch idleLatch = new CountDownLatch(CLIENT_COUNT);
56
57
58 server.getSessionConfig().setIdleTimeInMillis(IdleStatus.READ_IDLE, 2000);
59
60
61 server.bind(new InetSocketAddress(0));
62
63 final int boundPort = server.getServerSocketChannel().socket().getLocalPort();
64 server.setFilters(new IdleHandler(idleLatch));
65
66
67 final Socket[] clients = new Socket[CLIENT_COUNT];
68
69 for (int i = 0; i < CLIENT_COUNT; i++) {
70 clients[i] = new Socket("127.0.0.1", boundPort);
71 }
72
73 long start = System.currentTimeMillis();
74 try {
75 assertTrue("idle event missing ! ", idleLatch.await(4, TimeUnit.SECONDS));
76 System.err.println((System.currentTimeMillis() - start));
77 assertTrue(2000 <= (System.currentTimeMillis() - start));
78 } catch (final InterruptedException e) {
79 fail(e.getMessage());
80 }
81 }
82
83 private class IdleHandler extends AbstractIoFilter {
84
85 private final CountDownLatch latch;
86
87 public IdleHandler(final CountDownLatch latch) {
88 this.latch = latch;
89 }
90
91 @Override
92 public void sessionIdle(final IoSession session, final IdleStatus status) {
93 if (status == IdleStatus.READ_IDLE) {
94
95 latch.countDown();
96 session.close(true);
97 }
98 }
99 }
100 }