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