Search in sources :

Example 31 with Socket

use of java.net.Socket in project grpc-java by grpc.

the class ProxyTest method bigLatency.

@Test
public void bigLatency() throws UnknownHostException, IOException, InterruptedException, ExecutionException {
    server = new Server();
    int serverPort = server.init();
    executor.execute(server);
    int latency = (int) TimeUnit.MILLISECONDS.toNanos(250);
    proxy = new TrafficControlProxy(serverPort, 1024 * 1024, latency, TimeUnit.NANOSECONDS);
    startProxy(proxy).get();
    client = new Socket("localhost", proxy.getPort());
    DataOutputStream clientOut = new DataOutputStream(client.getOutputStream());
    DataInputStream clientIn = new DataInputStream(client.getInputStream());
    byte[] message = new byte[1];
    // warmup
    for (int i = 0; i < 5; i++) {
        clientOut.write(message, 0, 1);
    }
    clientIn.readFully(new byte[5]);
    // test
    long start = System.nanoTime();
    clientOut.write(message, 0, 1);
    clientIn.read(message);
    long stop = System.nanoTime();
    long rtt = (stop - start);
    assertEquals(latency, rtt, latency);
}
Also used : DataOutputStream(java.io.DataOutputStream) DataInputStream(java.io.DataInputStream) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) Test(org.junit.Test)

Example 32 with Socket

use of java.net.Socket in project grpc-java by grpc.

the class ProxyTest method smallLatency.

@Test
public void smallLatency() throws UnknownHostException, IOException, InterruptedException, ExecutionException {
    server = new Server();
    int serverPort = server.init();
    executor.execute(server);
    int latency = (int) TimeUnit.MILLISECONDS.toNanos(50);
    proxy = new TrafficControlProxy(serverPort, 1024 * 1024, latency, TimeUnit.NANOSECONDS);
    startProxy(proxy).get();
    client = new Socket("localhost", proxy.getPort());
    client.setReuseAddress(true);
    DataOutputStream clientOut = new DataOutputStream(client.getOutputStream());
    DataInputStream clientIn = new DataInputStream(client.getInputStream());
    byte[] message = new byte[1];
    // warmup
    for (int i = 0; i < 5; i++) {
        clientOut.write(message, 0, 1);
    }
    clientIn.readFully(new byte[5]);
    // test
    long start = System.nanoTime();
    clientOut.write(message, 0, 1);
    clientIn.read(message);
    long stop = System.nanoTime();
    long rtt = (stop - start);
    assertEquals(latency, rtt, latency);
}
Also used : DataOutputStream(java.io.DataOutputStream) DataInputStream(java.io.DataInputStream) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) Test(org.junit.Test)

Example 33 with Socket

use of java.net.Socket in project grpc-java by grpc.

the class ProxyTest method smallBandwidth.

@Test
public void smallBandwidth() throws UnknownHostException, IOException, InterruptedException, ExecutionException {
    server = new Server();
    int serverPort = server.init();
    server.setMode("stream");
    executor.execute(server);
    assertEquals(server.mode(), "stream");
    int bandwidth = 64 * 1024;
    proxy = new TrafficControlProxy(serverPort, bandwidth, 200, TimeUnit.MILLISECONDS);
    startProxy(proxy).get();
    client = new Socket("localhost", proxy.getPort());
    DataOutputStream clientOut = new DataOutputStream(client.getOutputStream());
    DataInputStream clientIn = new DataInputStream(client.getInputStream());
    clientOut.write(new byte[1]);
    clientIn.readFully(new byte[100 * 1024]);
    long start = System.nanoTime();
    clientIn.readFully(new byte[5 * bandwidth]);
    long stop = System.nanoTime();
    long bandUsed = ((5 * bandwidth) / ((stop - start) / TimeUnit.SECONDS.toNanos(1)));
    assertEquals(bandwidth, bandUsed, .5 * bandwidth);
}
Also used : DataOutputStream(java.io.DataOutputStream) DataInputStream(java.io.DataInputStream) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) Test(org.junit.Test)

Example 34 with Socket

use of java.net.Socket in project grpc-java by grpc.

the class OkHttpClientTransport method start.

@Override
public Runnable start(Listener listener) {
    this.listener = Preconditions.checkNotNull(listener, "listener");
    if (enableKeepAlive) {
        scheduler = SharedResourceHolder.get(TIMER_SERVICE);
        keepAliveManager = new KeepAliveManager(this, scheduler, keepAliveDelayNanos, keepAliveTimeoutNanos, false);
        keepAliveManager.onTransportStarted();
    }
    frameWriter = new AsyncFrameWriter(this, serializingExecutor);
    outboundFlow = new OutboundFlowController(this, frameWriter);
    // Connecting in the serializingExecutor, so that some stream operations like synStream
    // will be executed after connected.
    serializingExecutor.execute(new Runnable() {

        @Override
        public void run() {
            if (isForTest()) {
                if (connectingCallback != null) {
                    connectingCallback.run();
                }
                clientFrameHandler = new ClientFrameHandler(testFrameReader);
                executor.execute(clientFrameHandler);
                synchronized (lock) {
                    maxConcurrentStreams = Integer.MAX_VALUE;
                    startPendingStreams();
                }
                frameWriter.becomeConnected(testFrameWriter, socket);
                connectedFuture.set(null);
                return;
            }
            // Use closed source on failure so that the reader immediately shuts down.
            BufferedSource source = Okio.buffer(new Source() {

                @Override
                public long read(Buffer sink, long byteCount) {
                    return -1;
                }

                @Override
                public Timeout timeout() {
                    return Timeout.NONE;
                }

                @Override
                public void close() {
                }
            });
            Variant variant = new Http2();
            BufferedSink sink;
            Socket sock;
            try {
                if (proxyAddress == null) {
                    sock = new Socket(address.getAddress(), address.getPort());
                } else {
                    sock = createHttpProxySocket(address, proxyAddress, proxyUsername, proxyPassword);
                }
                if (sslSocketFactory != null) {
                    sock = OkHttpTlsUpgrader.upgrade(sslSocketFactory, sock, getOverridenHost(), getOverridenPort(), connectionSpec);
                }
                sock.setTcpNoDelay(true);
                source = Okio.buffer(Okio.source(sock));
                sink = Okio.buffer(Okio.sink(sock));
            } catch (StatusException e) {
                startGoAway(0, ErrorCode.INTERNAL_ERROR, e.getStatus());
                return;
            } catch (Exception e) {
                onException(e);
                return;
            } finally {
                clientFrameHandler = new ClientFrameHandler(variant.newReader(source, true));
                executor.execute(clientFrameHandler);
            }
            FrameWriter rawFrameWriter;
            synchronized (lock) {
                socket = sock;
                maxConcurrentStreams = Integer.MAX_VALUE;
                startPendingStreams();
            }
            rawFrameWriter = variant.newWriter(sink, true);
            frameWriter.becomeConnected(rawFrameWriter, socket);
            try {
                // Do these with the raw FrameWriter, so that they will be done in this thread,
                // and before any possible pending stream operations.
                rawFrameWriter.connectionPreface();
                Settings settings = new Settings();
                rawFrameWriter.settings(settings);
            } catch (Exception e) {
                onException(e);
                return;
            }
        }
    });
    return null;
}
Also used : Buffer(okio.Buffer) Http2(io.grpc.okhttp.internal.framed.Http2) BufferedSink(okio.BufferedSink) BufferedSource(okio.BufferedSource) Source(okio.Source) EOFException(java.io.EOFException) StatusException(io.grpc.StatusException) IOException(java.io.IOException) FrameWriter(io.grpc.okhttp.internal.framed.FrameWriter) Variant(io.grpc.okhttp.internal.framed.Variant) StatusException(io.grpc.StatusException) KeepAliveManager(io.grpc.internal.KeepAliveManager) Socket(java.net.Socket) Settings(io.grpc.okhttp.internal.framed.Settings) BufferedSource(okio.BufferedSource)

Example 35 with Socket

use of java.net.Socket in project grpc-java by grpc.

the class OkHttpClientTransportTest method proxy_500.

@Test
public void proxy_500() throws Exception {
    ServerSocket serverSocket = new ServerSocket(0);
    clientTransport = new OkHttpClientTransport(InetSocketAddress.createUnresolved("theservice", 80), "authority", "userAgent", executor, null, ConnectionSpec.CLEARTEXT, DEFAULT_MAX_MESSAGE_SIZE, (InetSocketAddress) serverSocket.getLocalSocketAddress(), null, null);
    clientTransport.start(transportListener);
    Socket sock = serverSocket.accept();
    serverSocket.close();
    BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream(), UTF_8));
    assertEquals("CONNECT theservice:80 HTTP/1.1", reader.readLine());
    assertEquals("Host: theservice:80", reader.readLine());
    while (!"".equals(reader.readLine())) {
    }
    final String errorText = "text describing error";
    sock.getOutputStream().write("HTTP/1.1 500 OH NO\r\n\r\n".getBytes(UTF_8));
    sock.getOutputStream().write(errorText.getBytes(UTF_8));
    sock.getOutputStream().flush();
    sock.shutdownOutput();
    assertEquals(-1, sock.getInputStream().read());
    ArgumentCaptor<Status> captor = ArgumentCaptor.forClass(Status.class);
    verify(transportListener, timeout(TIME_OUT_MS)).transportShutdown(captor.capture());
    Status error = captor.getValue();
    assertTrue("Status didn't contain error code: " + captor.getValue(), error.getDescription().contains("500"));
    assertTrue("Status didn't contain error description: " + captor.getValue(), error.getDescription().contains("OH NO"));
    assertTrue("Status didn't contain error text: " + captor.getValue(), error.getDescription().contains(errorText));
    assertEquals("Not UNAVAILABLE: " + captor.getValue(), Status.UNAVAILABLE.getCode(), error.getCode());
    sock.close();
    verify(transportListener, timeout(TIME_OUT_MS)).transportTerminated();
}
Also used : Status(io.grpc.Status) InputStreamReader(java.io.InputStreamReader) InetSocketAddress(java.net.InetSocketAddress) BufferedReader(java.io.BufferedReader) ServerSocket(java.net.ServerSocket) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) Test(org.junit.Test)

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