@SuppressWarnings("InfiniteLoopStatement")
        public void run() {
            Thread.currentThread().setName("GatewayThread");
            try {
                gatewaySocket = (SSLServerSocket)sslFactory.createServerSocket(gatewayPort);
                gatewaySocket.setNeedClientAuth(true);
            } catch (IOException e) {
                messages.release();
                throw new RuntimeException(e);
            }

            InputStream in = null;
            effectiveGatewayPort = gatewaySocket.getLocalPort();

            try {
                // Listen for connections
                startUp.release();
                while (true) {
                    Socket socket = gatewaySocket.accept();
                    // Work around JVM deadlock ... https://community.oracle.com/message/10989561#10989561
                    socket.setSoLinger(true, 1);

                    // Create streams to securely send and receive data to the client
                    in = socket.getInputStream();
                    gatewayOutputStream = socket.getOutputStream();
                    gatewayOutLock.release();

                    // Read from in and write to out...
                    byte[] read = readFully(in);

                    waitBeforeSend();
                    received.write(read);
                    messages.release();


                    waitForError.acquire();

                    // Close the socket
                    in.close();
                    gatewayOutputStream.close();
                }
            } catch (Throwable e) {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException ioex) {
                    LOGGER.warn("Can not close socket properly", ioex);
                }
                try {
                    if (gatewayOutputStream != null) {
                        gatewayOutputStream.close();
                    }
                } catch (IOException ioex) {
                    LOGGER.warn("Can not close gatewayOutputStream properly", ioex);
                }
                messages.release();
            }
        }
Create an ApnsServerStub that uses any free port for gateway and feedback.

@return the server stub. Use getEffectiveGatewayPort() and getEffectiveFeedbackPort() to ask for ports.
src/test/java/com/notnoop/apns/utils/ApnsServerStub.java