summaryrefslogtreecommitdiffstats
path: root/tests/CoreTests/android/core/DatagramTest.java
blob: 355a267edcdc46528bd06fcad85d0bf0e73584cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.core;

import junit.framework.TestCase;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import android.test.suitebuilder.annotation.LargeTest;

/**
 * Implements some simple tests for datagrams. Not as excessive as the core
 * tests, but good enough for the harness.
 */
public class DatagramTest extends TestCase {

    /**
     * Helper class that listens to incoming datagrams and reflects them to the
     * sender. Incoming datagram is interpreted as a String. It is uppercased
     * before being sent back.
     */

    class Reflector extends Thread {
        // Helper class for reflecting incoming datagrams. 
        DatagramSocket socket;

        boolean alive = true;

        byte[] buffer = new byte[256];

        DatagramPacket packet;

        /**
         * Main loop. Receives datagrams and reflects them.
         */
        @Override
        public void run() {
            try {
                while (alive) {
                    try {
                        packet.setLength(buffer.length);
                        socket.receive(packet);
                        String s = stringFromPacket(packet);
                        // System.out.println(s + " (from " + packet.getAddress() + ":" + packet.getPort() + ")");

                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException ex) {
                            // Ignore.
                        }

                        stringToPacket(s.toUpperCase(), packet);

                        packet.setAddress(InetAddress.getLocalHost());
                        packet.setPort(2345);

                        socket.send(packet);
                    } catch (java.io.InterruptedIOException e) {
                    }
                }
            } catch (java.io.IOException ex) {
                ex.printStackTrace();
            } finally {
                socket.close();
            }
        }

        /**
         * Creates a new Relfector object for the given local address and port.
         */
        public Reflector(int port, InetAddress address) {
            try {
                packet = new DatagramPacket(buffer, buffer.length);
                socket = new DatagramSocket(port, address);
            } catch (IOException ex) {
                throw new RuntimeException(
                        "Creating datagram reflector failed", ex);
            }
        }
    }

    /**
     * Converts a given datagram packet's contents to a String.
     */
    static String stringFromPacket(DatagramPacket packet) {
        return new String(packet.getData(), 0, packet.getLength());
    }

    /**
     * Converts a given String into a datagram packet.
     */
    static void stringToPacket(String s, DatagramPacket packet) {
        byte[] bytes = s.getBytes();
        System.arraycopy(bytes, 0, packet.getData(), 0, bytes.length);
        packet.setLength(bytes.length);
    }

    /**
     * Implements the main part of the Datagram test.
     */
    @LargeTest
    public void testDatagram() throws Exception {

        Reflector reflector = null;
        DatagramSocket socket = null;

        try {
            // Setup the reflector, so we have a partner to send to
            reflector = new Reflector(1234, InetAddress.getLocalHost());
            reflector.start();

            byte[] buffer = new byte[256];

            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            socket = new DatagramSocket(2345, InetAddress.getLocalHost());

            // Send ten simple packets and check for the expected responses.
            for (int i = 1; i <= 10; i++) {
                String s = "Hello, Android world #" + i + "!";
                stringToPacket(s, packet);

                packet.setAddress(InetAddress.getLocalHost());
                packet.setPort(1234);

                socket.send(packet);

                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    // Ignore.
                }

                packet.setLength(buffer.length);
                socket.receive(packet);
                String t = stringFromPacket(packet);
                // System.out.println(t + " (from " + packet.getAddress() + ":" + packet.getPort() + ")");

                assertEquals(s.toUpperCase(), t);
            }
        } finally {
            if (reflector != null) {
                reflector.alive = false;
            }

            if (socket != null) {
                socket.close();
            }
        }
    }

    // Regression test for issue 1018003: DatagramSocket ignored a set timeout.
    @LargeTest
    public void testDatagramSocketSetSOTimeout() throws Exception {
        DatagramSocket sock = null;
        int timeout = 5000;
        long start = System.currentTimeMillis();
        try {
            sock = new DatagramSocket();
            DatagramPacket pack = new DatagramPacket(new byte[100], 100);
            sock.setSoTimeout(timeout);
            sock.receive(pack);
        } catch (SocketTimeoutException e) {
            // expected
            long delay = System.currentTimeMillis() - start;
            if (Math.abs(delay - timeout) > 1000) {
                fail("timeout was not accurate. expected: " + timeout
                        + " actual: " + delay + " miliseconds.");
            }
        } finally {
            if (sock != null) {
                sock.close();
            }
        }
    }
}