SocketTest.java revision 249c40b94b9f5c8944a44be8e30aa01a90f1cf48
1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package org.apache.harmony.luni.tests.java.net;
19
20import java.io.IOException;
21import java.io.InputStream;
22import java.io.OutputStream;
23import java.net.ConnectException;
24import java.net.Inet4Address;
25import java.net.Inet6Address;
26import java.net.InetAddress;
27import java.net.InetSocketAddress;
28import java.net.Proxy;
29import java.net.ServerSocket;
30import java.net.Socket;
31import java.net.SocketAddress;
32import java.net.SocketException;
33import java.net.SocketImpl;
34import java.net.SocketImplFactory;
35import java.net.SocketTimeoutException;
36import java.net.UnknownHostException;
37import java.security.Permission;
38import java.util.Arrays;
39import java.util.Locale;
40
41import tests.support.Support_Configuration;
42
43public class SocketTest extends junit.framework.TestCase {
44    private class ClientThread implements Runnable {
45
46        public void run() {
47            try {
48                Socket socket = new Socket();
49                InetSocketAddress addr = new InetSocketAddress(host, port);
50                socket.connect(addr);
51
52                socket.close();
53            } catch (IOException e) {
54                throw new RuntimeException(e);
55            }
56        }
57    }
58
59    private class ServerThread implements Runnable {
60        private static final int FIRST_TIME = 1;
61
62        private static final int SECOND_TIME = 2;
63
64        private int backlog = 10;
65
66        public boolean ready = false;
67
68        private int serverSocketConstructor = 0;
69
70        public void run() {
71            try {
72
73                ServerSocket socket = null;
74                switch (serverSocketConstructor) {
75                case FIRST_TIME:
76                    socket = new ServerSocket(port, backlog,
77                            new InetSocketAddress(host, port).getAddress());
78                    port = socket.getLocalPort();
79                    break;
80                case SECOND_TIME:
81                    socket = new ServerSocket(port, backlog);
82                    host = socket.getInetAddress().getHostName();
83                    port = socket.getLocalPort();
84                    break;
85                default:
86                    socket = new ServerSocket();
87                    break;
88                }
89
90                synchronized (this) {
91                    ready = true;
92                    this.notifyAll();
93                }
94
95                socket.setSoTimeout(5000);
96                Socket client = socket.accept();
97                client.close();
98                socket.close();
99            } catch (IOException e) {
100                e.printStackTrace();
101            } catch (Throwable e) {
102                e.printStackTrace();
103            }
104        }
105
106        public synchronized void waitCreated() throws Exception {
107            while (!ready) {
108                this.wait();
109            }
110        }
111    }
112
113    boolean interrupted;
114
115    String host = "localhost";
116    int port;
117
118    Thread t;
119
120    private void connectTestImpl(int ssConsType) throws Exception {
121        ServerThread server = new ServerThread();
122        server.serverSocketConstructor = ssConsType;
123        Thread serverThread = new Thread(server);
124        serverThread.start();
125        server.waitCreated();
126
127        ClientThread client = new ClientThread();
128        Thread clientThread = new Thread(client);
129        clientThread.start();
130        try {
131            serverThread.join();
132            clientThread.join();
133        } catch (InterruptedException e) {
134            e.printStackTrace();
135        }
136    }
137
138    protected void tearDown() {
139        try {
140            if (t != null) {
141                t.interrupt();
142            }
143        } catch (Exception e) {
144        }
145        this.t = null;
146        this.interrupted = false;
147    }
148
149    /**
150     * @tests java.net.Socket#bind(java.net.SocketAddress)
151     */
152    public void test_bindLjava_net_SocketAddress() throws IOException {
153
154        @SuppressWarnings("serial")
155        class UnsupportedSocketAddress extends SocketAddress {
156            public UnsupportedSocketAddress() {
157            }
158        }
159
160        // Address we cannot bind to
161        Socket theSocket = new Socket();
162        InetSocketAddress bogusAddress = new InetSocketAddress(InetAddress
163                .getByAddress(Support_Configuration.nonLocalAddressBytes), 42);
164        try {
165            theSocket.bind(bogusAddress);
166            fail("No exception when binding to bad address");
167        } catch (IOException ex) {
168            // Expected
169        }
170        theSocket.close();
171
172        // Now create a socket that is not bound and then bind it
173        theSocket = new Socket();
174        theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
175        int portNumber = theSocket.getLocalPort();
176
177        // Validate that the localSocketAddress reflects the address we
178        // bound to
179        assertEquals("Local address not correct after bind",
180                new InetSocketAddress(InetAddress.getLocalHost(), portNumber),
181                theSocket.getLocalSocketAddress());
182
183        // Make sure we can now connect and that connections appear to come
184        // from the address we bound to.
185        InetSocketAddress theAddress = new InetSocketAddress(InetAddress
186                .getLocalHost(), 0);
187        ServerSocket server = new ServerSocket();
188        server.bind(theAddress);
189        int sport = server.getLocalPort();
190        InetSocketAddress boundAddress = new InetSocketAddress(InetAddress
191                .getLocalHost(), sport);
192
193        theSocket.connect(boundAddress);
194        Socket worker = server.accept();
195        assertEquals(
196                "Returned Remote address from server connected to does not match expected local address",
197                new InetSocketAddress(InetAddress.getLocalHost(), portNumber),
198                worker.getRemoteSocketAddress());
199        theSocket.close();
200        worker.close();
201        server.close();
202
203        // Validate if we pass in null that it picks an address for us and
204        // all is ok
205        theSocket = new Socket();
206        theSocket.bind(null);
207        assertNotNull("Bind with null did not work", theSocket
208                .getLocalSocketAddress());
209        theSocket.close();
210
211        // now check the error conditions
212
213        // Address that we have already bound to
214        theSocket = new Socket();
215        theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
216        theSocket.bind(theAddress);
217
218        Socket theSocket2 = new Socket();
219        try {
220            theSocket2.bind(theSocket.getLocalSocketAddress());
221            fail("No exception binding to address that is not available");
222        } catch (IOException ex) {
223            // Expected
224        }
225        theSocket.close();
226        theSocket2.close();
227
228        // Unsupported SocketAddress subclass
229        theSocket = new Socket();
230        try {
231            theSocket.bind(new UnsupportedSocketAddress());
232            fail("No exception when binding using unsupported SocketAddress subclass");
233        } catch (IllegalArgumentException ex) {
234            // Expected
235        }
236        theSocket.close();
237    }
238
239    /**
240     * @tests java.net.Socket#bind(java.net.SocketAddress)
241     */
242    public void test_bindLjava_net_SocketAddress_Proxy() throws IOException {
243        // The Proxy will not impact on the bind operation. It can be assigned
244        // with any address.
245        Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(
246                "127.0.0.1", 0));
247        Socket socket = new Socket(proxy);
248
249        InetAddress address = InetAddress.getByName("localhost");
250        socket.bind(new InetSocketAddress(address, 0));
251
252        assertEquals(address, socket.getLocalAddress());
253        assertTrue(0 != socket.getLocalPort());
254
255        socket.close();
256    }
257
258    public void test_close() throws IOException {
259        ServerSocket server = new ServerSocket(0);
260        Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
261
262        client.setSoLinger(false, 100);
263
264        client.close();
265        try {
266            client.getOutputStream();
267            fail("Failed to close socket");
268        } catch (IOException expected) {
269        }
270
271        server.close();
272    }
273
274    public void test_connect_unknownhost() throws Exception {
275        Socket socket = new Socket();
276        try {
277            socket.connect(new InetSocketAddress("unknownhost.invalid", 12345));
278            fail();
279        } catch (UnknownHostException expected) {
280        }
281    }
282
283    public void test_connect_unresolved() throws IOException {
284        Socket socket = new Socket();
285        InetSocketAddress unresolved = InetSocketAddress.createUnresolved("www.apache.org", 80);
286        try {
287            socket.connect(unresolved);
288            fail();
289        } catch (UnknownHostException expected) {
290        }
291        try {
292            socket.connect(unresolved, 123);
293            fail();
294        } catch (UnknownHostException expected) {
295        }
296    }
297
298    public void test_connectLjava_net_SocketAddress() throws Exception {
299
300        @SuppressWarnings("serial")
301        class UnsupportedSocketAddress extends SocketAddress {
302            public UnsupportedSocketAddress() {
303            }
304        }
305
306        Socket theSocket = new Socket();
307        try {
308            theSocket.connect(null);
309            fail("No exception for null arg");
310        } catch (IllegalArgumentException e) {
311            // Expected
312        }
313
314        try {
315            theSocket.connect(new UnsupportedSocketAddress());
316            fail("No exception for invalid socket address");
317        } catch (IllegalArgumentException e) {
318            // Expected
319        }
320
321        try {
322            theSocket.connect(new InetSocketAddress(InetAddress
323                    .getByAddress(new byte[] { 0, 0, 0, 0 }), 42));
324            fail("No exception with non-connectable address");
325        } catch (ConnectException e) {
326            // Expected
327        }
328
329        // now validate that we get a connect exception if we try to connect to
330        // an address on which nobody is listening
331        theSocket = new Socket();
332        try {
333            theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(),
334                    0));
335            fail("No exception when connecting to address nobody listening on");
336        } catch (ConnectException e) {
337            // Expected
338        }
339
340        // Now validate that we can actually connect when somebody is listening
341        ServerSocket server = new ServerSocket(0);
342        InetSocketAddress boundAddress = new InetSocketAddress(InetAddress
343                .getLocalHost(), server.getLocalPort());
344        Socket client = new Socket();
345        client.connect(boundAddress);
346
347        // validate that when a socket is connected that it answers
348        // correctly to related queries
349        assertTrue("Wrong connected status", client.isConnected());
350        assertFalse("Wrong closed status", client.isClosed());
351        assertTrue("Wrong bound status", client.isBound());
352        assertFalse("Wrong input shutdown status", client.isInputShutdown());
353        assertFalse("Wrong output shutdown status", client.isOutputShutdown());
354        assertTrue("Local port was 0", client.getLocalPort() != 0);
355
356        client.close();
357        server.close();
358
359        // Now validate that we get the right exception if we connect when we
360        // are already connected
361        server = new ServerSocket(0);
362        boundAddress = new InetSocketAddress(InetAddress.getLocalHost(), server
363                .getLocalPort());
364        client = new Socket();
365        client.connect(boundAddress);
366
367        try {
368            client.connect(boundAddress);
369            fail("No exception when we try to connect on a connected socket: ");
370        } catch (SocketException e) {
371            // Expected
372        }
373        client.close();
374        server.close();
375    }
376
377    /**
378     * Regression for Harmony-2503
379     */
380    public void test_connectLjava_net_SocketAddress_AnyAddress()
381            throws Exception {
382        connectTestImpl(ServerThread.FIRST_TIME);
383        connectTestImpl(ServerThread.SECOND_TIME);
384    }
385
386    /**
387     * @tests java.net.Socket#connect(java.net.SocketAddress, int)
388     */
389    public void test_connectLjava_net_SocketAddressI() throws Exception {
390
391        @SuppressWarnings("serial")
392        class UnsupportedSocketAddress extends SocketAddress {
393            public UnsupportedSocketAddress() {
394            }
395        }
396
397        // Start by validating the error checks
398        Socket theSocket = new Socket();
399        try {
400            theSocket.connect(new InetSocketAddress(0), -100);
401            fail("No exception for negative timeout");
402        } catch (IllegalArgumentException e) {
403            // Expected
404        }
405
406        try {
407            theSocket.connect(null, 0);
408            fail("No exception for null address");
409        } catch (IllegalArgumentException e) {
410            // Expected
411        }
412
413        try {
414            theSocket.connect(new UnsupportedSocketAddress(), 1000);
415            fail("No exception for invalid socket address type");
416        } catch (IllegalArgumentException e) {
417            // Expected
418        }
419
420        SocketAddress nonConnectableAddress = new InetSocketAddress(InetAddress
421                .getByAddress(new byte[] { 0, 0, 0, 0 }), 0);
422        try {
423            theSocket.connect(nonConnectableAddress, 1000);
424            fail("No exception when non Connectable Address passed in: ");
425        } catch (SocketException e) {
426            // Expected
427        }
428
429        // Now validate that we get a connect exception if we try to connect to
430        // an address on which nobody is listening
431        theSocket = new Socket();
432        try {
433            theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(),
434                    0), 0);
435            fail("No exception when connecting to address nobody listening on");
436        } catch (ConnectException e) {
437            // Expected
438        }
439        theSocket.close();
440
441        // Now validate that we can actually connect when somebody is listening
442        ServerSocket server = new ServerSocket(0);
443        InetSocketAddress boundAddress = new InetSocketAddress(InetAddress
444                .getLocalHost(), server.getLocalPort());
445        Socket client = new Socket();
446        client.connect(boundAddress, 0);
447
448        // Validate that when a socket is connected that it answers
449        // correctly to related queries
450        assertTrue("Wrong connected status", client.isConnected());
451        assertFalse("Wrong closed status", client.isClosed());
452        assertTrue("Wrong bound status", client.isBound());
453        assertFalse("Wrong input shutdown status", client.isInputShutdown());
454        assertFalse("Wrong output shutdown status", client.isOutputShutdown());
455        assertTrue("Local port was 0", client.getLocalPort() != 0);
456
457        client.close();
458        server.close();
459
460        // Now validate that we get a connect exception if we try to connect to
461        // an address on which nobody is listening
462        theSocket = new Socket();
463        SocketAddress nonListeningAddress = new InetSocketAddress(InetAddress
464                .getLocalHost(), 42);
465        try {
466            theSocket.connect(nonListeningAddress, 1000);
467            fail("No exception when connecting to address nobody listening on");
468        } catch (ConnectException e) {
469            // Expected
470        } catch (SocketTimeoutException e) {
471            // The other possibility is that the system timed us out.
472        }
473        theSocket.close();
474
475        // Now validate that we get the right exception if we connect when we
476        // are already connected
477        server = new ServerSocket(0);
478        boundAddress = new InetSocketAddress(InetAddress.getLocalHost(), server
479                .getLocalPort());
480        client = new Socket();
481        client.connect(boundAddress, 10000);
482
483        try {
484            client.connect(boundAddress, 10000);
485            fail("No exception when we try to connect on a connected socket: ");
486        } catch (SocketException e) {
487            // Expected
488        }
489        client.close();
490        server.close();
491    }
492
493    /**
494     * @tests java.net.Socket#Socket()
495     */
496    public void test_Constructor() {
497        // create the socket and then validate some basic state
498        Socket s = new Socket();
499        assertFalse("new socket should not be connected", s.isConnected());
500        assertFalse("new socket should not be bound", s.isBound());
501        assertFalse("new socket should not be closed", s.isClosed());
502        assertFalse("new socket should not be in InputShutdown", s
503                .isInputShutdown());
504        assertFalse("new socket should not be in OutputShutdown", s
505                .isOutputShutdown());
506    }
507
508    /**
509     * @tests java.net.Socket#Socket(java.lang.String, int)
510     */
511    public void test_ConstructorLjava_lang_StringI() throws IOException {
512        ServerSocket server = new ServerSocket(0);
513        Socket client = new Socket(InetAddress.getLocalHost(), server
514                .getLocalPort());
515
516        assertEquals("Failed to create socket", server.getLocalPort(), client
517                .getPort());
518
519        // Regression for HARMONY-946
520        ServerSocket ss = new ServerSocket(0);
521        Socket s = new Socket("0.0.0.0", ss.getLocalPort());
522        ss.close();
523        s.close();
524    }
525
526    /**
527     * @tests java.net.Socket#Socket(java.lang.String, int,
528     *        java.net.InetAddress, int)
529     */
530    public void test_ConstructorLjava_lang_StringILjava_net_InetAddressI()
531            throws IOException {
532
533        ServerSocket server = new ServerSocket(0);
534        int serverPort = server.getLocalPort();
535        Socket client = new Socket(InetAddress.getLocalHost().getHostName(),
536                serverPort, InetAddress.getLocalHost(), 0);
537        assertTrue("Failed to create socket", client.getPort() == serverPort);
538        client.close();
539
540        Socket theSocket = null;
541        try {
542            theSocket = new Socket("127.0.0.1", serverPort, InetAddress
543                    .getLocalHost(), 0);
544        } catch (IOException e) {
545            // check here if InetAddress.getLocalHost() is returning the
546            // loopback address, if so that is likely the cause of the failure
547            assertFalse(
548                    "Misconfiguration - local host is the loopback address",
549                    InetAddress.getLocalHost().isLoopbackAddress());
550            throw e;
551        }
552
553        assertTrue(theSocket.isConnected());
554
555        try {
556            new Socket("127.0.0.1", serverPort, theSocket.getLocalAddress(),
557                    theSocket.getLocalPort());
558            fail("Was able to create two sockets on same port");
559        } catch (IOException e) {
560            // Expected
561        }
562
563        theSocket.close();
564        server.close();
565    }
566
567    @SuppressWarnings("deprecation")
568    public void test_ConstructorLjava_lang_StringIZ() throws IOException {
569        ServerSocket server = new ServerSocket(0);
570        int serverPort = server.getLocalPort();
571        Socket client = new Socket(InetAddress.getLocalHost().getHostAddress(),
572                serverPort, true);
573
574        assertEquals("Failed to create socket", serverPort, client.getPort());
575        client.close();
576
577        client = new Socket(InetAddress.getLocalHost().getHostName(),
578                serverPort, false);
579        client.close();
580        server.close();
581    }
582
583    /**
584     * @tests java.net.Socket#Socket(java.net.InetAddress, int)
585     */
586    public void test_ConstructorLjava_net_InetAddressI() throws IOException {
587        ServerSocket server = new ServerSocket(0);
588        Socket client = new Socket(InetAddress.getLocalHost(), server
589                .getLocalPort());
590
591        assertEquals("Failed to create socket", server.getLocalPort(), client
592                .getPort());
593
594        client.close();
595        server.close();
596    }
597
598    /**
599     * @tests java.net.Socket#Socket(java.net.InetAddress, int,
600     *        java.net.InetAddress, int)
601     */
602    public void test_ConstructorLjava_net_InetAddressILjava_net_InetAddressI()
603            throws IOException {
604        ServerSocket server = new ServerSocket(0);
605        Socket client = new Socket(InetAddress.getLocalHost(), server
606                .getLocalPort(), InetAddress.getLocalHost(), 0);
607        assertNotSame("Failed to create socket", 0, client.getLocalPort());
608    }
609
610    /**
611     * @tests java.net.Socket#Socket(java.net.InetAddress, int, boolean)
612     */
613    @SuppressWarnings("deprecation")
614    public void test_ConstructorLjava_net_InetAddressIZ() throws IOException {
615        ServerSocket server = new ServerSocket(0);
616        int serverPort = server.getLocalPort();
617
618        Socket client = new Socket(InetAddress.getLocalHost(), serverPort, true);
619        assertEquals("Failed to create socket", serverPort, client.getPort());
620
621        client = new Socket(InetAddress.getLocalHost(), serverPort, false);
622        client.close();
623    }
624
625    /**
626     * @tests java.net.Socket#Socket(Proxy)
627     */
628    public void test_ConstructorLjava_net_Proxy_Exception() {
629
630        SocketAddress addr1 = InetSocketAddress.createUnresolved("127.0.0.1",
631                80);
632        SocketAddress addr2 = new InetSocketAddress("localhost", 80);
633
634        Proxy proxy1 = new Proxy(Proxy.Type.HTTP, addr1);
635        // IllegalArgumentException test
636        try {
637            new Socket(proxy1);
638            fail("should throw IllegalArgumentException");
639        } catch (IllegalArgumentException e) {
640            // expected
641        }
642
643        Proxy proxy2 = new Proxy(Proxy.Type.SOCKS, addr1);
644        // should not throw any exception
645        new Socket(proxy2);
646        new Socket(Proxy.NO_PROXY);
647    }
648
649    /**
650     * @tests java.net.Socket#getChannel()
651     */
652    public void test_getChannel() {
653        assertNull(new Socket().getChannel());
654    }
655
656    /**
657     * @tests java.net.Socket#getInetAddress()
658     */
659    public void test_getInetAddress() throws IOException {
660        ServerSocket server = new ServerSocket(0);
661        Socket client = new Socket(InetAddress.getLocalHost(), server
662                .getLocalPort());
663
664        assertTrue("Returned incorrect InetAdrees", client.getInetAddress()
665                .equals(InetAddress.getLocalHost()));
666
667        client.close();
668        server.close();
669    }
670
671    /**
672     * @tests java.net.Socket#getInputStream()
673     */
674    public void test_getInputStream() throws IOException {
675        // Simple fetch test
676        ServerSocket server = new ServerSocket(0);
677        Socket client = new Socket(InetAddress.getLocalHost(), server
678                .getLocalPort());
679        InputStream is = client.getInputStream();
680        assertNotNull("Failed to get stream", is);
681        is.close();
682        client.close();
683        server.close();
684    }
685
686    private boolean isUnix() {
687        String osName = System.getProperty("os.name");
688
689        // only comparing ASCII, so assume english locale
690        osName = (osName == null ? null : osName.toLowerCase(Locale.ENGLISH));
691
692        if (osName != null && osName.startsWith("windows")) { //$NON-NLS-1$
693            return false;
694        }
695        return true;
696    }
697
698    public void test_getKeepAlive() throws Exception {
699        ServerSocket server = new ServerSocket(0);
700        Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort(), null, 0);
701
702        client.setKeepAlive(true);
703        assertTrue("getKeepAlive false when it should be true", client.getKeepAlive());
704
705        client.setKeepAlive(false);
706        assertFalse("getKeepAlive true when it should be False", client.getKeepAlive());
707    }
708
709    public void test_getLocalAddress() throws IOException {
710        ServerSocket server = new ServerSocket(0);
711        Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
712
713        assertTrue("Returned incorrect InetAddress", client.getLocalAddress()
714                .equals(InetAddress.getLocalHost()));
715
716        client = new Socket();
717        client.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
718        assertTrue(client.getLocalAddress().isAnyLocalAddress());
719
720        client.close();
721        server.close();
722    }
723
724    /**
725     * @tests java.net.Socket#getLocalPort()
726     */
727    public void test_getLocalPort() throws IOException {
728        ServerSocket server = new ServerSocket(0);
729        Socket client = new Socket(InetAddress.getLocalHost(), server
730                .getLocalPort());
731
732        assertNotSame("Returned incorrect port", 0, client.getLocalPort());
733
734        client.close();
735        server.close();
736    }
737
738    public void test_getLocalSocketAddress() throws IOException {
739        // set up server connect and then validate that we get the right
740        // response for the local address
741        ServerSocket server = new ServerSocket(0);
742        Socket client = new Socket(InetAddress.getLocalHost(), server
743                .getLocalPort());
744        int clientPort = client.getLocalPort();
745
746        assertEquals("Returned incorrect InetSocketAddress(1):",
747                new InetSocketAddress(InetAddress.getLocalHost(), clientPort),
748                client.getLocalSocketAddress());
749        client.close();
750        server.close();
751
752        // now create a socket that is not bound and validate we get the
753        // right answer
754        client = new Socket();
755        assertNull(
756                "Returned incorrect InetSocketAddress -unbound socket- Expected null",
757                client.getLocalSocketAddress());
758
759        // now bind the socket and make sure we get the right answer
760        client.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
761        clientPort = client.getLocalPort();
762        assertEquals("Returned incorrect InetSocketAddress(2):",
763                new InetSocketAddress(InetAddress.getLocalHost(), clientPort),
764                client.getLocalSocketAddress());
765        client.close();
766
767        // now validate the behaviour when the any address is returned
768        client = new Socket();
769        client.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
770        assertTrue(((InetSocketAddress) client.getLocalSocketAddress()).getAddress().isAnyLocalAddress());
771        client.close();
772
773        // now validate the same for getLocalAddress
774        client = new Socket();
775        client.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
776        assertTrue(client.getLocalAddress().isAnyLocalAddress());
777        client.close();
778    }
779
780    public void test_getOOBInline() throws Exception {
781        Socket theSocket = new Socket();
782
783        theSocket.setOOBInline(true);
784        assertTrue("expected OOBIline to be true", theSocket.getOOBInline());
785
786        theSocket.setOOBInline(false);
787        assertFalse("expected OOBIline to be false", theSocket.getOOBInline());
788
789        theSocket.setOOBInline(false);
790        assertFalse("expected OOBIline to be false", theSocket.getOOBInline());
791    }
792
793    /**
794     * @tests java.net.Socket#getOutputStream()
795     */
796    @SuppressWarnings("deprecation")
797    public void test_getOutputStream() throws IOException {
798        // Simple fetch test
799        ServerSocket server = new ServerSocket(0);
800        Socket client = new Socket(InetAddress.getLocalHost(), server
801                .getLocalPort());
802        OutputStream os = client.getOutputStream();
803        assertNotNull("Failed to get stream", os);
804        os.close();
805        client.close();
806        server.close();
807
808        // Simple read/write test over the IO streams
809        final ServerSocket sinkServer = new ServerSocket(0);
810        Runnable runnable = new Runnable() {
811            public void run() {
812                try {
813                    Socket worker = sinkServer.accept();
814                    sinkServer.close();
815                    InputStream in = worker.getInputStream();
816                    in.read();
817                    in.close();
818                    worker.close();
819                } catch (IOException e) {
820                    fail();
821                }
822            }
823        };
824        Thread thread = new Thread(runnable, "Socket.getOutputStream");
825        thread.start();
826
827        Socket pingClient = new Socket(InetAddress.getLocalHost(), sinkServer
828                .getLocalPort());
829
830        // Busy wait until the client is connected.
831        int c = 0;
832        while (!pingClient.isConnected()) {
833            try {
834                Thread.sleep(200);
835            } catch (InterruptedException e) {
836            }
837            if (++c > 4) {
838                fail("thread is not alive");
839            }
840        }
841
842        // Write some data to the server
843        OutputStream out = pingClient.getOutputStream();
844        out.write(new byte[256]);
845
846        // Wait for the server to finish
847        Thread.yield();
848        c = 0;
849        while (thread.isAlive()) {
850            try {
851                Thread.sleep(200);
852            } catch (InterruptedException e) {
853            }
854            if (++c > 4) {
855                fail("read call did not exit");
856            }
857        }
858
859        // Subsequent writes should throw an exception
860        try {
861            // The output buffer may remain valid until the close completes
862            for (int i = 0; i < 400; i++) {
863                out.write(new byte[256]);
864            }
865            fail("write to closed socket did not cause exception");
866        } catch (IOException e) {
867            // Expected
868        }
869
870        out.close();
871        pingClient.close();
872        sinkServer.close();
873
874        // Regression test for HARMONY-873
875        ServerSocket ss2 = new ServerSocket(0);
876        Socket s = new Socket("127.0.0.1", ss2.getLocalPort());
877        ss2.accept();
878        s.shutdownOutput();
879        try {
880            s.getOutputStream();
881            fail("should throw SocketException");
882        } catch (SocketException e) {
883            // expected
884        }
885    }
886
887    public void test_getPort() throws IOException {
888        ServerSocket server = new ServerSocket(0);
889        int serverPort = server.getLocalPort();
890        Socket client = new Socket(InetAddress.getLocalHost(), serverPort);
891
892        assertEquals("Returned incorrect port", serverPort, client.getPort());
893
894        client.close();
895        server.close();
896    }
897
898    public void test_getReceiveBufferSize() throws Exception {
899        ServerSocket server = new ServerSocket(0);
900        Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
901        client.setReceiveBufferSize(130);
902
903        assertTrue("Incorrect buffer size", client.getReceiveBufferSize() >= 130);
904
905        client.close();
906        server.close();
907    }
908
909    /**
910     * @tests java.net.Socket#getRemoteSocketAddress()
911     */
912    public void test_getRemoteSocketAddress() throws IOException {
913        // set up server connect and then validate that we get the right
914        // response for the remote address
915        ServerSocket server = new ServerSocket(0);
916        int serverPort = server.getLocalPort();
917        Socket client = new Socket(InetAddress.getLocalHost(), serverPort);
918
919        assertEquals("Returned incorrect InetSocketAddress(1):",
920                new InetSocketAddress(InetAddress.getLocalHost(), serverPort),
921                client.getRemoteSocketAddress());
922        client.close();
923
924        // now create one that is not connected and validate that we get the
925        // right answer
926        Socket theSocket = new Socket();
927        theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
928        assertNull("Returned incorrect InetSocketAddress -unconnected socket:",
929                theSocket.getRemoteSocketAddress());
930
931        // now connect and validate we get the right answer
932        theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(),
933                serverPort));
934        assertEquals("Returned incorrect InetSocketAddress(2):",
935                new InetSocketAddress(InetAddress.getLocalHost(), serverPort),
936                theSocket.getRemoteSocketAddress());
937        theSocket.close();
938
939        server.close();
940    }
941
942    public void test_getReuseAddress() throws Exception {
943        Socket theSocket = new Socket();
944        theSocket.setReuseAddress(true);
945        assertTrue("getReuseAddress false when it should be true", theSocket.getReuseAddress());
946        theSocket.setReuseAddress(false);
947        assertFalse("getReuseAddress true when it should be False", theSocket.getReuseAddress());
948    }
949
950    public void test_getSendBufferSize() throws Exception {
951        ServerSocket server = new ServerSocket(0);
952        Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
953        client.setSendBufferSize(134);
954        assertTrue("Incorrect buffer size", client.getSendBufferSize() >= 134);
955        client.close();
956        server.close();
957    }
958
959    public void test_getSoLinger() throws Exception {
960        ServerSocket server = new ServerSocket(0);
961        Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
962        client.setSoLinger(true, 200);
963        assertEquals("Returned incorrect linger", 200, client.getSoLinger());
964        client.setSoLinger(false, 0);
965        client.close();
966        server.close();
967    }
968
969    public void test_getSoTimeout() throws Exception {
970        ServerSocket server = new ServerSocket(0);
971        Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
972        client.setSoTimeout(100);
973        assertEquals("Returned incorrect sotimeout", 100, client.getSoTimeout());
974        client.close();
975        server.close();
976    }
977
978    public void test_getTcpNoDelay() throws Exception {
979        ServerSocket server = new ServerSocket(0);
980        Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
981
982        boolean bool = !client.getTcpNoDelay();
983        client.setTcpNoDelay(bool);
984        assertTrue("Failed to get no delay setting: " + client.getTcpNoDelay(), client.getTcpNoDelay() == bool);
985
986        client.close();
987        server.close();
988    }
989
990    public void test_getTrafficClass() throws Exception {
991        /*
992         * We cannot actually check that the values are set as if a platform
993         * does not support the option then it may come back unset even
994         * though we set it so just get the value to make sure we can get it
995         */
996        int trafficClass = new Socket().getTrafficClass();
997        assertTrue(0 <= trafficClass);
998        assertTrue(trafficClass <= 255);
999    }
1000
1001    /**
1002     * @tests java.net.Socket#isBound()
1003     */
1004    public void test_isBound() throws IOException {
1005        ServerSocket server = new ServerSocket(0);
1006        Socket client = new Socket(InetAddress.getLocalHost(), server
1007                .getLocalPort());
1008        Socket worker = server.accept();
1009
1010        assertTrue("Socket indicated  not bound when it should be (1)", client
1011                .isBound());
1012        worker.close();
1013        client.close();
1014        server.close();
1015
1016        client = new Socket();
1017        assertFalse("Socket indicated bound when it was not (2)", client
1018                .isBound());
1019
1020        server = new ServerSocket();
1021        server.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
1022        InetSocketAddress boundAddress = new InetSocketAddress(server
1023                .getInetAddress(), server.getLocalPort());
1024        client.connect(boundAddress);
1025        worker = server.accept();
1026        assertTrue("Socket indicated not bound when it should be (2)", client
1027                .isBound());
1028        worker.close();
1029        client.close();
1030        server.close();
1031
1032        // now test when we bind explicitly
1033        InetSocketAddress theLocalAddress = new InetSocketAddress(InetAddress
1034                .getLocalHost(), 0);
1035        client = new Socket();
1036        assertFalse("Socket indicated bound when it was not (3)", client
1037                .isBound());
1038        client.bind(theLocalAddress);
1039        assertTrue("Socket indicated not bound when it should be (3a)", client
1040                .isBound());
1041        client.close();
1042        assertTrue("Socket indicated not bound when it should be (3b)", client
1043                .isBound());
1044    }
1045
1046    /**
1047     * @tests java.net.Socket#isClosed()
1048     */
1049    public void test_isClosed() throws IOException {
1050        ServerSocket server = new ServerSocket(0);
1051        Socket client = new Socket(InetAddress.getLocalHost(), server
1052                .getLocalPort());
1053        Socket worker = server.accept();
1054
1055        // validate isClosed returns expected values
1056        assertFalse("Socket should indicate it is not closed(1):", client
1057                .isClosed());
1058        client.close();
1059        assertTrue("Socket should indicate it is closed(1):", client.isClosed());
1060
1061        // validate that isClosed works ok for sockets returned from
1062        // ServerSocket.accept()
1063        assertFalse("Accepted Socket should indicate it is not closed:", worker
1064                .isClosed());
1065        worker.close();
1066        assertTrue("Accepted Socket should indicate it is closed:", worker
1067                .isClosed());
1068
1069        // and finally for the server socket
1070        assertFalse("Server Socket should indicate it is not closed:", server
1071                .isClosed());
1072        server.close();
1073        assertTrue("Server Socket should indicate it is closed:", server
1074                .isClosed());
1075    }
1076
1077    /**
1078     * @tests java.net.Socket#isConnected()
1079     */
1080    public void test_isConnected() throws IOException {
1081        ServerSocket server = new ServerSocket(0);
1082        Socket client = new Socket(InetAddress.getLocalHost(), server
1083                .getLocalPort());
1084        Socket worker = server.accept();
1085
1086        assertTrue("Socket indicated  not connected when it should be", client
1087                .isConnected());
1088        client.close();
1089        worker.close();
1090        server.close();
1091
1092        // now do it with the new constructors and revalidate
1093        InetSocketAddress theAddress = new InetSocketAddress(InetAddress
1094                .getLocalHost(), 0);
1095        client = new Socket();
1096        assertFalse("Socket indicated connected when it was not", client
1097                .isConnected());
1098
1099        server = new ServerSocket();
1100        server.bind(theAddress);
1101        InetSocketAddress boundAddress = new InetSocketAddress(server
1102                .getInetAddress(), server.getLocalPort());
1103        client.connect(boundAddress);
1104        worker = server.accept();
1105        assertTrue("Socket indicated  not connected when it should be", client
1106                .isConnected());
1107        client.close();
1108        worker.close();
1109        server.close();
1110    }
1111
1112    /**
1113     * @tests java.net.Socket#isInputShutdown()
1114     */
1115    public void test_isInputShutdown() throws IOException {
1116        ServerSocket server = new ServerSocket(0);
1117        Socket client = new Socket(InetAddress.getLocalHost(), server
1118                .getLocalPort());
1119
1120        Socket worker = server.accept();
1121        InputStream theInput = client.getInputStream();
1122        OutputStream theOutput = worker.getOutputStream();
1123
1124        // make sure we get the right answer with newly connected socket
1125        assertFalse("Socket indicated input shutdown when it should not have",
1126                client.isInputShutdown());
1127
1128        // shutdown the output
1129        client.shutdownInput();
1130
1131        // make sure we get the right answer once it is shut down
1132        assertTrue(
1133                "Socket indicated input was NOT shutdown when it should have been",
1134                client.isInputShutdown());
1135
1136        client.close();
1137        worker.close();
1138        server.close();
1139
1140        // make sure we get the right answer for closed sockets
1141        assertFalse(
1142                "Socket indicated input was shutdown when socket was closed",
1143                worker.isInputShutdown());
1144
1145        theInput.close();
1146        theOutput.close();
1147    }
1148
1149    /**
1150     * @tests java.net.Socket#isOutputShutdown()
1151     */
1152    public void test_isOutputShutdown() throws IOException {
1153        ServerSocket server = new ServerSocket(0);
1154        Socket client = new Socket(InetAddress.getLocalHost(), server
1155                .getLocalPort());
1156
1157        Socket worker = server.accept();
1158        InputStream theInput = client.getInputStream();
1159        OutputStream theOutput = worker.getOutputStream();
1160
1161        // make sure we get the right answer with newly connected socket
1162        assertFalse("Socket indicated output shutdown when it should not have",
1163                worker.isOutputShutdown());
1164
1165        // shutdown the output
1166        worker.shutdownOutput();
1167
1168        // make sure we get the right answer once it is shut down
1169        assertTrue(
1170                "Socket indicated output was NOT shutdown when it should have been",
1171                worker.isOutputShutdown());
1172
1173        client.close();
1174        worker.close();
1175        server.close();
1176
1177        // make sure we get the right answer for closed sockets
1178        assertFalse(
1179                "Socket indicated output was output shutdown when the socket was closed",
1180                client.isOutputShutdown());
1181
1182        theInput.close();
1183        theOutput.close();
1184    }
1185
1186    /**
1187     * @tests java.net.Socket#sendUrgentData(int)
1188     */
1189    public void test_sendUrgentDataI() throws Exception {
1190        /*
1191         * Some platforms may not support urgent data in this case we will not
1192         * run these tests. For now run on all platforms until we find those
1193         * that do not support urgent data
1194         */
1195        String platform = System.getProperty("os.name");
1196        if (platform.equals("Dummy")) {
1197            return;
1198        }
1199
1200        /*
1201         * Test 1: Validate that when OOBInline is false that any urgent data is
1202         * silently ignored
1203         */
1204        InetAddress localHost = InetAddress.getLocalHost();
1205        ServerSocket server = new ServerSocket(0, 5, localHost);
1206        SocketAddress serverAddress = new InetSocketAddress(localHost, server
1207                .getLocalPort());
1208
1209        Socket client = new Socket();
1210        client.setOOBInline(false);
1211
1212        client.connect(serverAddress);
1213        Socket worker = server.accept();
1214        worker.setTcpNoDelay(true);
1215        OutputStream theOutput = worker.getOutputStream();
1216
1217        // Send the regular data
1218        byte[] sendBytes = new String("Test").getBytes();
1219        theOutput.write(sendBytes);
1220        theOutput.flush();
1221
1222        // Send the urgent data byte which should not be received
1223        worker.sendUrgentData("UrgentData".getBytes()[0]);
1224        theOutput.write(sendBytes);
1225        worker.shutdownOutput();
1226        worker.close();
1227
1228        // Try to read the bytes back
1229        int totalBytesRead = 0;
1230        byte[] myBytes = new byte[100];
1231        InputStream theInput = client.getInputStream();
1232        while (true) {
1233            int bytesRead = theInput.read(myBytes, totalBytesRead,
1234                    myBytes.length - totalBytesRead);
1235            if (bytesRead == -1) {
1236                break;
1237            }
1238            totalBytesRead = totalBytesRead + bytesRead;
1239        }
1240
1241        client.close();
1242        server.close();
1243
1244        byte[] expectBytes = new byte[2 * sendBytes.length];
1245        System.arraycopy(sendBytes, 0, expectBytes, 0, sendBytes.length);
1246        System.arraycopy(sendBytes, 0, expectBytes, sendBytes.length,
1247                sendBytes.length);
1248
1249        byte[] resultBytes = new byte[totalBytesRead];
1250        System.arraycopy(myBytes, 0, resultBytes, 0, totalBytesRead);
1251
1252        assertTrue("Urgent data was received", Arrays.equals(expectBytes,
1253                resultBytes));
1254
1255        /*
1256         * Test 2: Now validate that urgent data is received as expected. Expect
1257         * that it should be between the two writes.
1258         */
1259        server = new ServerSocket(0, 5, localHost);
1260        serverAddress = new InetSocketAddress(localHost, server.getLocalPort());
1261
1262        client = new Socket();
1263        client.setOOBInline(true);
1264
1265        client.connect(serverAddress);
1266        worker = server.accept();
1267        worker.setTcpNoDelay(true);
1268        theOutput = worker.getOutputStream();
1269
1270        // Send the regular data
1271        sendBytes = new String("Test - Urgent Data").getBytes();
1272        theOutput.write(sendBytes);
1273
1274        // Send the urgent data (one byte) which should be received
1275        client.setOOBInline(true);
1276        byte urgentByte = "UrgentData".getBytes()[0];
1277        worker.sendUrgentData(urgentByte);
1278
1279        // Send more data, the urgent byte must stay in position
1280        theOutput.write(sendBytes);
1281        worker.shutdownOutput();
1282        worker.close();
1283
1284        // Try to read the bytes back
1285        totalBytesRead = 0;
1286        myBytes = new byte[100];
1287        theInput = client.getInputStream();
1288        while (true) {
1289            int bytesRead = theInput.read(myBytes, totalBytesRead,
1290                    myBytes.length - totalBytesRead);
1291            if (bytesRead == -1) {
1292                break;
1293            }
1294            totalBytesRead = totalBytesRead + bytesRead;
1295        }
1296
1297        client.close();
1298        server.close();
1299
1300        expectBytes = new byte[2 * sendBytes.length + 1];
1301        System.arraycopy(sendBytes, 0, expectBytes, 0, sendBytes.length);
1302        expectBytes[sendBytes.length] = urgentByte;
1303        System.arraycopy(sendBytes, 0, expectBytes, sendBytes.length + 1,
1304                sendBytes.length);
1305
1306        resultBytes = new byte[totalBytesRead];
1307        System.arraycopy(myBytes, 0, resultBytes, 0, totalBytesRead);
1308
1309        assertTrue("Urgent data was not received with one urgent byte", Arrays
1310                .equals(expectBytes, resultBytes));
1311
1312        /*
1313         * Test 3: Now validate that urgent data is received as expected. Expect
1314         * that it should be between the two writes.
1315         */
1316        server = new ServerSocket(0, 5, localHost);
1317        serverAddress = new InetSocketAddress(localHost, server.getLocalPort());
1318
1319        client = new Socket();
1320        client.setOOBInline(true);
1321
1322        client.connect(serverAddress);
1323        worker = server.accept();
1324        worker.setTcpNoDelay(true);
1325        theOutput = worker.getOutputStream();
1326
1327        // Send the regular data
1328        sendBytes = new String("Test - Urgent Data").getBytes();
1329        theOutput.write(sendBytes);
1330
1331        // Send the urgent data (one byte) which should be received
1332        client.setOOBInline(true);
1333        byte urgentByte1 = "UrgentData".getBytes()[0];
1334        byte urgentByte2 = "UrgentData".getBytes()[1];
1335        worker.sendUrgentData(urgentByte1);
1336        worker.sendUrgentData(urgentByte2);
1337
1338        // Send more data, the urgent byte must stay in position
1339        theOutput.write(sendBytes);
1340        worker.shutdownOutput();
1341        worker.close();
1342
1343        // Try to read the bytes back
1344        totalBytesRead = 0;
1345        myBytes = new byte[100];
1346        theInput = client.getInputStream();
1347        while (true) {
1348            int bytesRead = theInput.read(myBytes, totalBytesRead,
1349                    myBytes.length - totalBytesRead);
1350            if (bytesRead == -1) {
1351                break;
1352            }
1353            totalBytesRead = totalBytesRead + bytesRead;
1354        }
1355
1356        client.close();
1357        server.close();
1358
1359        expectBytes = new byte[2 * sendBytes.length + 2];
1360        System.arraycopy(sendBytes, 0, expectBytes, 0, sendBytes.length);
1361        expectBytes[sendBytes.length] = urgentByte1;
1362        expectBytes[sendBytes.length + 1] = urgentByte2;
1363        System.arraycopy(sendBytes, 0, expectBytes, sendBytes.length + 2,
1364                sendBytes.length);
1365
1366        resultBytes = new byte[totalBytesRead];
1367        System.arraycopy(myBytes, 0, resultBytes, 0, totalBytesRead);
1368
1369        assertTrue("Urgent data was not received with two urgent bytes", Arrays
1370                .equals(expectBytes, resultBytes));
1371
1372        /*
1373         * Test 4: Now test the case where there is only urgent data.
1374         */
1375        server = new ServerSocket(0, 5, localHost);
1376        serverAddress = new InetSocketAddress(localHost, server.getLocalPort());
1377
1378        client = new Socket();
1379        client.setOOBInline(true);
1380
1381        client.connect(serverAddress);
1382        worker = server.accept();
1383        worker.setTcpNoDelay(true);
1384
1385        // Send the urgent data (one byte) which should be received
1386        client.setOOBInline(true);
1387        urgentByte = "UrgentData".getBytes()[0];
1388        worker.sendUrgentData(urgentByte);
1389        worker.close();
1390
1391        // Try to read the bytes back
1392        theInput = client.getInputStream();
1393        int byteRead = theInput.read();
1394
1395        client.close();
1396        server.close();
1397
1398        assertEquals("Sole urgent data was not received",
1399                (int) (urgentByte & 0xff), byteRead);
1400    }
1401
1402    /**
1403     * @tests java.net.Socket#setKeepAlive(boolean)
1404     */
1405    public void test_setKeepAliveZ() throws IOException {
1406
1407        class TestSocket extends Socket {
1408            public TestSocket(SocketImpl impl) throws SocketException {
1409                super(impl);
1410            }
1411        }
1412
1413        // There is not really a good test for this as it is there to detect
1414        // crashed machines. Just make sure we can set it
1415        ServerSocket server = new ServerSocket(0);
1416        Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
1417
1418        client.setKeepAlive(true);
1419        client.setKeepAlive(false);
1420        client.close();
1421        server.close();
1422
1423        // Regression test for HARMONY-1136
1424        new TestSocket((SocketImpl) null).setKeepAlive(true);
1425    }
1426
1427    public void test_setOOBInlineZ() throws Exception {
1428        Socket theSocket = new Socket();
1429        theSocket.setOOBInline(true);
1430        assertTrue("expected OOBIline to be true", theSocket.getOOBInline());
1431    }
1432
1433    public void test_setPerformancePreference_Int_Int_Int() throws IOException {
1434        Socket theSocket = new Socket();
1435        theSocket.setPerformancePreferences(1, 1, 1);
1436    }
1437
1438    public void test_setReceiveBufferSizeI() throws Exception {
1439        ServerSocket server = new ServerSocket(0);
1440        Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
1441
1442        client.setReceiveBufferSize(130);
1443        assertTrue("Incorrect buffer size", client.getReceiveBufferSize() >= 130);
1444
1445        client.close();
1446        server.close();
1447    }
1448
1449    public void test_setReuseAddressZ() throws Exception {
1450        Socket theSocket = new Socket();
1451        theSocket.setReuseAddress(false);
1452        // Bind to any available port on the given address
1453        theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
1454        InetSocketAddress localAddress1 = new InetSocketAddress(theSocket.getLocalAddress(), theSocket.getLocalPort());
1455
1456        Socket theSocket2 = new Socket();
1457        theSocket2.setReuseAddress(false);
1458
1459        /*
1460         * Try to invoke a bind while the port is busy (TIME_WAIT). Note
1461         * that we may not succeed, which will cause the test to pass
1462         * without testing the reuseaddr behavior.
1463         */
1464        theSocket.close();
1465        theSocket2.bind(localAddress1);
1466
1467        theSocket2.close();
1468    }
1469
1470    public void test_setSendBufferSizeI() throws Exception {
1471        ServerSocket server = new ServerSocket(0);
1472        Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
1473        client.setSendBufferSize(134);
1474        assertTrue("Incorrect buffer size", client.getSendBufferSize() >= 134);
1475        client.close();
1476        server.close();
1477    }
1478
1479    public void test_setSocketImplFactoryLjava_net_SocketImplFactory() {
1480        // Cannot test as setting will cause the factory to be changed for
1481        // all subsequent sockets
1482    }
1483
1484    public void test_setSoLingerZI() throws IOException {
1485        ServerSocket server = new ServerSocket(0);
1486        Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
1487        client.setSoLinger(true, 500);
1488        assertEquals("Set incorrect linger", 500, client.getSoLinger());
1489        client.setSoLinger(false, 0);
1490        client.close();
1491        server.close();
1492    }
1493
1494    public void test_setSoTimeoutI() throws Exception {
1495        ServerSocket server = new ServerSocket(0);
1496        Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
1497        client.setSoTimeout(100);
1498        assertEquals("Set incorrect sotimeout", 100, client.getSoTimeout());
1499        client.close();
1500        server.close();
1501    }
1502
1503    public void test_setTcpNoDelayZ() throws Exception {
1504        ServerSocket server = new ServerSocket(0);
1505        Socket client = new Socket(InetAddress.getLocalHost(), server .getLocalPort());
1506
1507        boolean bool;
1508        client.setTcpNoDelay(bool = !client.getTcpNoDelay());
1509        assertTrue("Failed to set no delay setting: " + client.getTcpNoDelay(), client.getTcpNoDelay() == bool);
1510
1511        client.close();
1512        server.close();
1513    }
1514
1515    public void test_setTrafficClassI() throws Exception {
1516        int IPTOS_LOWCOST = 0x2;
1517        int IPTOS_RELIABILTY = 0x4;
1518        int IPTOS_THROUGHPUT = 0x8;
1519        int IPTOS_LOWDELAY = 0x10;
1520
1521        Socket theSocket = new Socket();
1522
1523        // validate that value set must be between 0 and 255
1524        try {
1525            theSocket.setTrafficClass(256);
1526            fail("No exception was thrown when traffic class set to 256");
1527        } catch (IllegalArgumentException expected) {
1528        }
1529
1530        try {
1531            theSocket.setTrafficClass(-1);
1532            fail("No exception was thrown when traffic class set to -1");
1533        } catch (IllegalArgumentException expected) {
1534        }
1535
1536        // now validate that we can set it to some good values
1537        theSocket.setTrafficClass(IPTOS_LOWCOST);
1538        theSocket.setTrafficClass(IPTOS_RELIABILTY);
1539        theSocket.setTrafficClass(IPTOS_THROUGHPUT);
1540        theSocket.setTrafficClass(IPTOS_LOWDELAY);
1541    }
1542
1543    @SuppressWarnings("deprecation")
1544    public void test_shutdownInput() throws IOException {
1545        ServerSocket server = new ServerSocket(0);
1546        int port = server.getLocalPort();
1547        Socket client = new Socket(InetAddress.getLocalHost(), port);
1548
1549        Socket worker = server.accept();
1550        worker.setTcpNoDelay(true);
1551
1552        InputStream theInput = client.getInputStream();
1553        OutputStream theOutput = worker.getOutputStream();
1554
1555        // shutdown the input
1556        client.shutdownInput();
1557
1558        // send the regular data
1559        String sendString = new String("Test");
1560        theOutput.write(sendString.getBytes());
1561        theOutput.flush();
1562
1563        // RI fails here. It is a RI bug not to return 0 to indicate EOF
1564        assertEquals(0, theInput.available());
1565
1566        client.close();
1567        server.close();
1568
1569        // Regression test for HARMONY-2944
1570        // Port 0 is not allowed to be used in connect() on some platforms,
1571        // Since server has been closed here, so the port is free now
1572        Socket s = new Socket("0.0.0.0", port, false);
1573        s.shutdownInput();
1574        try {
1575            s.shutdownInput();
1576            fail("should throw SocketException");
1577        } catch (SocketException se) {
1578            // Expected
1579        }
1580        s.close();
1581    }
1582
1583    /**
1584     * @tests java.net.Socket#shutdownOutput()
1585     */
1586    @SuppressWarnings("deprecation")
1587    public void test_shutdownOutput() throws IOException {
1588        ServerSocket server = new ServerSocket(0);
1589        int port = server.getLocalPort();
1590        Socket client = new Socket(InetAddress.getLocalHost(), port);
1591
1592        Socket worker = server.accept();
1593        OutputStream theOutput = worker.getOutputStream();
1594
1595        // shutdown the output
1596        worker.shutdownOutput();
1597
1598        // send the regular data
1599        String sendString = new String("Test");
1600        try {
1601            theOutput.write(sendString.getBytes());
1602            theOutput.flush();
1603            fail("No exception when writing on socket with output shutdown");
1604        } catch (IOException e) {
1605            // Expected
1606        }
1607
1608        client.close();
1609        server.close();
1610
1611        // Regression test for HARMONY-2944
1612        // Port 0 is not allowed to be used in connect() on some platforms,
1613        // Since server has been closed here, so the port is free now
1614        Socket s = new Socket("0.0.0.0", port, false);
1615        s.shutdownOutput();
1616        try {
1617            s.shutdownOutput();
1618            fail("should throw SocketException");
1619        } catch (SocketException se) {
1620            // Expected
1621        }
1622        s.close();
1623    }
1624
1625    public void test_toString() throws IOException {
1626        ServerSocket server = new ServerSocket(0);
1627        Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
1628        // RI has "addr" and "localport" instead of "address" and "localPort".
1629        String expected = "Socket[address=" + InetAddress.getLocalHost()
1630                + ",port=" + client.getPort() + ",localPort="
1631                + client.getLocalPort() + "]";
1632        assertEquals(expected, client.toString());
1633        client.close();
1634        server.close();
1635    }
1636}
1637