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