Code example for ServerSocket

Methods: bind, getLocalPort

0
     
    @Before 
    public void setup() throws IOException { 
        // Set up a socket listening on an arbitrary port.  
        serverSocket = ServerSocketFactory.getDefault().createServerSocket();
        serverSocket.bind(new InetSocketAddress(0));
 
        // Point serverURI at the socket. 
        try { 
            int port = serverSocket.getLocalPort();
            serverURI = new URI("http", null, "localhost", port, "/", null, null);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        } 
    } 
 
    @After 
    public void shutdown() throws IOException { 
        serverSocket.close();
    }