1/* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package libcore.java.net; 18 19import java.io.IOException; 20import java.net.Inet4Address; 21import java.net.InetSocketAddress; 22import java.net.ServerSocket; 23import java.net.Socket; 24 25public class ServerSocketTest extends junit.framework.TestCase { 26 public void testTimeoutAfterAccept() throws Exception { 27 final ServerSocket ss = new ServerSocket(0); 28 ss.setReuseAddress(true); 29 // On Unix, the receive timeout is inherited by the result of accept(2). 30 // Java specifies that it should always be 0 instead. 31 ss.setSoTimeout(1234); 32 final Socket[] result = new Socket[1]; 33 Thread t = new Thread(new Runnable() { 34 public void run() { 35 try { 36 result[0] = ss.accept(); 37 } catch (IOException ex) { 38 ex.printStackTrace(); 39 fail(); 40 } 41 } 42 }); 43 t.start(); 44 new Socket(ss.getInetAddress(), ss.getLocalPort()); 45 t.join(); 46 assertEquals(0, result[0].getSoTimeout()); 47 } 48 49 public void testInitialState() throws Exception { 50 ServerSocket ss = new ServerSocket(); 51 try { 52 assertFalse(ss.isBound()); 53 assertFalse(ss.isClosed()); 54 assertEquals(-1, ss.getLocalPort()); 55 assertNull(ss.getLocalSocketAddress()); 56 assertNull(ss.getInetAddress()); 57 assertTrue(ss.getReuseAddress()); 58 assertNull(ss.getChannel()); 59 } finally { 60 ss.close(); 61 } 62 } 63 64 public void testStateAfterClose() throws Exception { 65 ServerSocket ss = new ServerSocket(); 66 ss.bind(new InetSocketAddress(Inet4Address.getLocalHost(), 0)); 67 InetSocketAddress boundAddress = (InetSocketAddress) ss.getLocalSocketAddress(); 68 ss.close(); 69 70 assertTrue(ss.isBound()); 71 assertTrue(ss.isClosed()); 72 assertEquals(boundAddress.getAddress(), ss.getInetAddress()); 73 assertEquals(boundAddress.getPort(), ss.getLocalPort()); 74 75 InetSocketAddress localAddressAfterClose = (InetSocketAddress) ss.getLocalSocketAddress(); 76 assertEquals(boundAddress, localAddressAfterClose); 77 } 78} 79