Code example for ServerSocket

Methods: accept, close, getLocalPort

0
    /** 
     * @tests java.net.Socket#getInputStream() 
     */ 
    public void test_getInputStream() throws IOException { 
        // Simple read/write test over the IO streams 
        final ServerSocket pingServer = new ServerSocket(0);
        Socket pingClient = new Socket();
 
        try { 
            pingClient.connect(new InetSocketAddress(
                    InetAddress.getLocalHost(), pingServer.getLocalPort()));
 
            Socket worker = pingServer.accept();
            pingServer.close();
 
            // Write some data to the server to provoke it 
            OutputStream clientOut = pingClient.getOutputStream();
            clientOut.write(new byte[256]);
            InputStream in = worker.getInputStream();
            in.read();
 
            OutputStream out = worker.getOutputStream();
            out.write(new byte[42]);
            worker.close();
            InputStream clientIn = pingClient.getInputStream();
            clientIn.read(new byte[42]);
 
            try { 
                clientIn.read();
                fail("Should throw SocketException");
            } catch (SocketException e) {
                // expected 
            } 
            clientIn.close();
 
            try { 
                clientIn.read();
                fail("Should throw SocketException");
            } catch (SocketException e) {
                // expected 
            } 
            try { 
                clientIn.read(new byte[5]);
                fail("Should throw SocketException");
            } catch (SocketException e) {
                // expected 
            } 
        } finally { 
            pingClient.close();
            pingServer.close();
        } 
    } 
 
    public void test_connectLjava_net_SocketAddressI() throws Exception { 
        // Now validate that we get a interrupted exception if we try to connect