Search in sources :

Example 41 with Socket

use of java.net.Socket in project j2objc by google.

the class MockWebServer method serveConnection.

private void serveConnection(final Socket raw) {
    String name = "MockWebServer-" + raw.getRemoteSocketAddress();
    requestExecutor.execute(namedRunnable(name, new Runnable() {

        int sequenceNumber = 0;

        public void run() {
            try {
                processConnection();
            } catch (Exception e) {
                logger.log(Level.WARNING, "MockWebServer connection failed", e);
            }
        }

        public void processConnection() throws Exception {
            Socket socket;
            if (sslSocketFactory != null) {
                if (tunnelProxy) {
                    createTunnel();
                }
                SocketPolicy socketPolicy = dispatcher.peek().getSocketPolicy();
                if (socketPolicy == FAIL_HANDSHAKE) {
                    dispatchBookkeepingRequest(sequenceNumber, raw);
                    processHandshakeFailure(raw);
                    return;
                }
                socket = sslSocketFactory.createSocket(raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true);
                SSLSocket sslSocket = (SSLSocket) socket;
                sslSocket.setUseClientMode(false);
                openClientSockets.put(socket, true);
                sslSocket.startHandshake();
                openClientSockets.remove(raw);
            } else {
                socket = raw;
            }
            InputStream in = new BufferedInputStream(socket.getInputStream());
            OutputStream out = new BufferedOutputStream(socket.getOutputStream());
            while (processOneRequest(socket, in, out)) {
            }
            if (sequenceNumber == 0) {
                logger.warning("MockWebServer connection didn't make a request");
            }
            in.close();
            out.close();
            socket.close();
            openClientSockets.remove(socket);
        }

        /**
             * Respond to CONNECT requests until a SWITCH_TO_SSL_AT_END response
             * is dispatched.
             */
        private void createTunnel() throws IOException, InterruptedException {
            while (true) {
                SocketPolicy socketPolicy = dispatcher.peek().getSocketPolicy();
                if (!processOneRequest(raw, raw.getInputStream(), raw.getOutputStream())) {
                    throw new IllegalStateException("Tunnel without any CONNECT!");
                }
                if (socketPolicy == SocketPolicy.UPGRADE_TO_SSL_AT_END)
                    return;
            }
        }

        /**
             * Reads a request and writes its response. Returns true if a request
             * was processed.
             */
        private boolean processOneRequest(Socket socket, InputStream in, OutputStream out) throws IOException, InterruptedException {
            RecordedRequest request = readRequest(socket, in, out, sequenceNumber);
            if (request == null) {
                return false;
            }
            requestCount.incrementAndGet();
            requestQueue.add(request);
            MockResponse response = dispatcher.dispatch(request);
            if (response.getSocketPolicy() == SocketPolicy.DISCONNECT_AFTER_READING_REQUEST) {
                logger.info("Received request: " + request + " and disconnected without responding");
                return false;
            }
            writeResponse(out, response);
            if (response.getSocketPolicy() == SocketPolicy.DISCONNECT_AT_END) {
                in.close();
                out.close();
            } else if (response.getSocketPolicy() == SocketPolicy.SHUTDOWN_INPUT_AT_END) {
                socket.shutdownInput();
            } else if (response.getSocketPolicy() == SocketPolicy.SHUTDOWN_OUTPUT_AT_END) {
                socket.shutdownOutput();
            }
            logger.info("Received request: " + request + " and responded: " + response);
            sequenceNumber++;
            return true;
        }
    }));
}
Also used : BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) SSLSocket(javax.net.ssl.SSLSocket) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) SocketException(java.net.SocketException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UnknownHostException(java.net.UnknownHostException) BufferedInputStream(java.io.BufferedInputStream) BufferedOutputStream(java.io.BufferedOutputStream) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) ServerSocket(java.net.ServerSocket)

Example 42 with Socket

use of java.net.Socket in project j2objc by google.

the class InterruptedStreamTest method newSocketChannelPair.

/**
     * Returns a pair of connected sockets backed by NIO socket channels.
     */
private Socket[] newSocketChannelPair() throws IOException {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.socket().bind(new InetSocketAddress(0));
    SocketChannel clientSocketChannel = SocketChannel.open();
    clientSocketChannel.connect(serverSocketChannel.socket().getLocalSocketAddress());
    SocketChannel server = serverSocketChannel.accept();
    serverSocketChannel.close();
    return new Socket[] { clientSocketChannel.socket(), server.socket() };
}
Also used : ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) ServerSocketChannel(java.nio.channels.ServerSocketChannel) Socket(java.net.Socket)

Example 43 with Socket

use of java.net.Socket in project j2objc by google.

the class TestSSLContext method clientAuth.

/**
     * Returns an SSLSocketFactory that calls setWantClientAuth and
     * setNeedClientAuth as specified on all returned sockets.
     */
public static SSLSocketFactory clientAuth(final SSLSocketFactory sf, final boolean want, final boolean need) {
    return new SSLSocketFactory() {

        private SSLSocket set(Socket socket) {
            SSLSocket s = (SSLSocket) socket;
            s.setWantClientAuth(want);
            s.setNeedClientAuth(need);
            return s;
        }

        public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
            return set(sf.createSocket(host, port));
        }

        public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
            return set(sf.createSocket(host, port, localHost, localPort));
        }

        public Socket createSocket(InetAddress host, int port) throws IOException {
            return set(sf.createSocket(host, port));
        }

        public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
            return set(sf.createSocket(address, port));
        }

        public String[] getDefaultCipherSuites() {
            return sf.getDefaultCipherSuites();
        }

        public String[] getSupportedCipherSuites() {
            return sf.getSupportedCipherSuites();
        }

        public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
            return set(sf.createSocket(s, host, port, autoClose));
        }
    };
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) InetAddress(java.net.InetAddress) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) SSLServerSocket(javax.net.ssl.SSLServerSocket)

Example 44 with Socket

use of java.net.Socket in project j2objc by google.

the class SocketTest method testReadAfterClose.

public void testReadAfterClose() throws Exception {
    MockServer server = new MockServer();
    server.enqueue(new byte[] { 5, 3 }, 0);
    Socket socket = new Socket("localhost", server.port);
    InputStream in = socket.getInputStream();
    assertEquals(5, in.read());
    assertEquals(3, in.read());
    assertEquals(-1, in.read());
    assertEquals(-1, in.read());
    socket.close();
    in.close();
    /*
         * Rather astonishingly, read() doesn't throw even though the stream is
         * closed. This is consistent with the RI's behavior.
         */
    assertEquals(-1, in.read());
    assertEquals(-1, in.read());
    server.shutdown();
}
Also used : InputStream(java.io.InputStream) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket)

Example 45 with Socket

use of java.net.Socket in project j2objc by google.

the class SocketTest method test_getLocalAddress_after_close.

/**
     * Our getLocalAddress and getLocalPort currently use getsockname(3).
     * This means they give incorrect results on closed sockets (as well
     * as requiring an unnecessary call into native code).
     */
public void test_getLocalAddress_after_close() throws Exception {
    Socket s = new Socket();
    try {
        // Bind to an ephemeral local port.
        s.bind(new InetSocketAddress("localhost", 0));
        assertTrue(s.getLocalAddress().toString(), s.getLocalAddress().isLoopbackAddress());
        // What local port did we get?
        int localPort = s.getLocalPort();
        assertTrue(localPort > 0);
        // Now close the socket...
        s.close();
        // The RI returns the ANY address but the original local port after close.
        assertTrue(s.getLocalAddress().isAnyLocalAddress());
        assertEquals(localPort, s.getLocalPort());
    } finally {
        s.close();
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket)

Aggregations

Socket (java.net.Socket)1630 IOException (java.io.IOException)703 ServerSocket (java.net.ServerSocket)577 OutputStream (java.io.OutputStream)376 InetSocketAddress (java.net.InetSocketAddress)367 Test (org.junit.Test)361 InputStream (java.io.InputStream)259 InputStreamReader (java.io.InputStreamReader)178 BufferedReader (java.io.BufferedReader)159 SocketException (java.net.SocketException)137 SSLSocket (javax.net.ssl.SSLSocket)110 SocketTimeoutException (java.net.SocketTimeoutException)97 UnknownHostException (java.net.UnknownHostException)86 ConnectException (java.net.ConnectException)84 InetAddress (java.net.InetAddress)78 ByteArrayOutputStream (java.io.ByteArrayOutputStream)76 OutputStreamWriter (java.io.OutputStreamWriter)70 DataOutputStream (java.io.DataOutputStream)68 ServletOutputStream (javax.servlet.ServletOutputStream)68 CountDownLatch (java.util.concurrent.CountDownLatch)65