1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.example.echoserver;
21
22 import static org.junit.Assert.assertEquals;
23 import static org.junit.Assert.assertTrue;
24 import static org.junit.Assert.fail;
25
26 import java.net.DatagramPacket;
27 import java.net.DatagramSocket;
28 import java.net.InetSocketAddress;
29 import java.net.Socket;
30 import java.net.SocketTimeoutException;
31 import java.util.Arrays;
32
33 import org.apache.mina.example.echoserver.ssl.SslServerSocketFactory;
34 import org.apache.mina.example.echoserver.ssl.SslSocketFactory;
35 import org.junit.Test;
36
37
38
39
40
41
42 public class AcceptorTest extends AbstractTest {
43 public AcceptorTest() {
44 }
45
46 @Test
47 public void testTCP() throws Exception {
48 testTCP0(new Socket("127.0.0.1", port));
49 }
50
51 @Test
52 public void testTCPWithSSL() throws Exception {
53
54 useSSL = true;
55
56
57 SslSocketFactory.setSslEnabled(true);
58 SslServerSocketFactory.setSslEnabled(true);
59 testTCP0(SslSocketFactory.getSocketFactory().createSocket(
60 "localhost", port));
61 }
62
63 private void testTCP0(Socket client) throws Exception {
64 client.setSoTimeout(3000);
65 byte[] writeBuf = new byte[16];
66
67 for (int i = 0; i < 10; i++) {
68 fillWriteBuffer(writeBuf, i);
69 client.getOutputStream().write(writeBuf);
70 }
71
72 byte[] readBuf = new byte[writeBuf.length];
73
74 for (int i = 0; i < 10; i++) {
75 fillWriteBuffer(writeBuf, i);
76
77 int readBytes = 0;
78 while (readBytes < readBuf.length) {
79 int nBytes = client.getInputStream().read(readBuf, readBytes,
80 readBuf.length - readBytes);
81
82 if (nBytes < 0) {
83 fail("Unexpected disconnection.");
84 }
85
86 readBytes += nBytes;
87 }
88
89 assertTrue(Arrays.equals( writeBuf, readBuf));
90 }
91
92 client.setSoTimeout(500);
93
94 try {
95 client.getInputStream().read();
96 fail("Unexpected incoming data.");
97 } catch (SocketTimeoutException e) {
98 }
99
100 client.getInputStream().close();
101 client.close();
102 }
103
104 public void testUDP() throws Exception {
105 DatagramSocket client = new DatagramSocket();
106 client.connect(new InetSocketAddress("127.0.0.1", port));
107 client.setSoTimeout(500);
108
109 byte[] writeBuf = new byte[16];
110 byte[] readBuf = new byte[writeBuf.length];
111 DatagramPacket wp = new DatagramPacket(writeBuf, writeBuf.length);
112 DatagramPacket rp = new DatagramPacket(readBuf, readBuf.length);
113
114 for (int i = 0; i < 10; i++) {
115 fillWriteBuffer(writeBuf, i);
116 client.send(wp);
117
118 client.receive(rp);
119 assertEquals(writeBuf.length, rp.getLength());
120 assertTrue(Arrays.equals(writeBuf, readBuf));
121 }
122
123 try {
124 client.receive(rp);
125 fail("Unexpected incoming data.");
126 } catch (SocketTimeoutException e) {
127 }
128
129 client.close();
130 }
131
132 private void fillWriteBuffer(byte[] writeBuf, int i) {
133 for (int j = writeBuf.length - 1; j >= 0; j--) {
134 writeBuf[j] = (byte) (j + i);
135 }
136 }
137 }