List of usage examples for java.nio.channels SocketChannel write
public final long write(ByteBuffer[] srcs) throws IOException
From source file:com.alexkli.jhb.Worker.java
@Override public void run() { try {//from w w w.j a v a 2 s . com while (true) { long start = System.nanoTime(); QueueItem<HttpRequestBase> item = queue.take(); idleAvg.add(System.nanoTime() - start); if (item.isPoisonPill()) { return; } HttpRequestBase request = item.getRequest(); if ("java".equals(config.client)) { System.setProperty("http.keepAlive", "false"); item.sent(); try { HttpURLConnection http = (HttpURLConnection) new URL(request.getURI().toString()) .openConnection(); http.setConnectTimeout(5000); http.setReadTimeout(5000); int statusCode = http.getResponseCode(); consumeAndCloseStream(http.getInputStream()); if (statusCode == 200) { item.done(); } else { item.failed(); } } catch (IOException e) { System.err.println("Failed request: " + e.getMessage()); e.printStackTrace(); // System.exit(2); item.failed(); } } else if ("ahc".equals(config.client)) { try { item.sent(); try (CloseableHttpResponse response = httpClient.execute(request, context)) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { item.done(); } else { item.failed(); } } } catch (IOException e) { System.err.println("Failed request: " + e.getMessage()); item.failed(); } } else if ("fast".equals(config.client)) { try { URI uri = request.getURI(); item.sent(); InetAddress addr = InetAddress.getByName(uri.getHost()); Socket socket = new Socket(addr, uri.getPort()); PrintWriter out = new PrintWriter(socket.getOutputStream()); // BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // send an HTTP request to the web server out.println("GET / HTTP/1.1"); out.append("Host: ").append(uri.getHost()).append(":").println(uri.getPort()); out.println("Connection: Close"); out.println(); out.flush(); // read the response consumeAndCloseStream(socket.getInputStream()); // boolean loop = true; // StringBuilder sb = new StringBuilder(8096); // while (loop) { // if (in.ready()) { // int i = 0; // while (i != -1) { // i = in.read(); // sb.append((char) i); // } // loop = false; // } // } item.done(); socket.close(); } catch (IOException e) { e.printStackTrace(); item.failed(); } } else if ("nio".equals(config.client)) { URI uri = request.getURI(); item.sent(); String requestBody = "GET / HTTP/1.1\n" + "Host: " + uri.getHost() + ":" + uri.getPort() + "\n" + "Connection: Close\n\n"; try { InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort()); SocketChannel channel = SocketChannel.open(); channel.socket().setSoTimeout(5000); channel.connect(addr); ByteBuffer msg = ByteBuffer.wrap(requestBody.getBytes()); channel.write(msg); msg.clear(); ByteBuffer buf = ByteBuffer.allocate(1024); int count; while ((count = channel.read(buf)) != -1) { buf.flip(); byte[] bytes = new byte[count]; buf.get(bytes); buf.clear(); } channel.close(); item.done(); } catch (IOException e) { e.printStackTrace(); item.failed(); } } } } catch (InterruptedException e) { System.err.println("Worker thread [" + this.toString() + "] was interrupted: " + e.getMessage()); } }
From source file:idgs.client.SocketChannelHandler.java
/** * handle write message//ww w . ja v a2 s .c om * @param channel * @param ctx * @throws IOException */ public void onWrite(SocketChannel channel) throws IOException { ClientActorMessage msg = (ClientActorMessage) context.getAttachment(); if (msg != null) { // write header byte[] bodyBytes = msg.toBuffer(); final int bodyBytesLen = bodyBytes.length; RpcBuffer buffer = new RpcBuffer(); buffer.encodeHeader(); buffer.setHeader(bodyBytesLen); buffer.flip(); int writeHeaderBytes = channel.write(buffer.getBody()); if (writeHeaderBytes > 0) { log.debug("writer header content: " + bodyBytesLen); log.debug("byte size: " + writeHeaderBytes + ", order by " + buffer.getByteOrder().toString() + " bytes: " + Arrays.toString(buffer.array())); buffer.setBodyLength(bodyBytesLen); buffer.encodeHeader(); buffer.setBody(bodyBytes); buffer.flip(); int writeBodyBytes = channel.write(buffer.getBody()); if (writeBodyBytes > 0) { log.debug("writer body content: " + new String(bodyBytes)); log.debug("byte size: " + bodyBytesLen + ", order by " + buffer.getByteOrder().toString() + " bytes: " + Arrays.toString(buffer.array())); } else { log.warn("write body nothing..."); } } else { log.warn("write header nothing..."); } } }
From source file:org.cloudata.core.commitlog.pipe.Bulk.java
public OperationResult write(SocketChannel ch) throws IOException { if (bufferList.size() == 0) { throw new IOException("Pipe is closed"); }/*from w ww. ja v a2s . c o m*/ int numWritten = 0; while (true) { ByteBuffer readBuf = bufferList.get(currentWriteBufIndex); ByteBuffer writeBuffer = readBuf.duplicate(); writeBuffer.position(writtenPos); writeBuffer.limit(readBuf.position()); numWritten = ch.write(writeBuffer); writtenPos += numWritten; totalNumWritten += numWritten; if (writeBuffer.hasRemaining()) { return OperationResult.partially; } //LOG.info("totalNumWritten : " + totalNumWritten + ", totalNumRead : " + totalNumRead); if (totalNumWritten < totalNumRead) { if (currentWriteBufIndex < currentReadBufIndex) { currentWriteBufIndex++; writtenPos = 0; } else { return OperationResult.partially; } } else { return OperationResult.completed; } } }
From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(timeOut = 15000) public void testTunnelToEchoServer() throws IOException { MockServer proxyServer = startConnectProxyServer(); Tunnel tunnel = Tunnel.build("localhost", doubleEchoServer.getServerSocketPort(), "localhost", proxyServer.getServerSocketPort()); try {// w ww. ja v a2s . c om int tunnelPort = tunnel.getPort(); SocketChannel client = SocketChannel.open(); client.connect(new InetSocketAddress("localhost", tunnelPort)); client.write(ByteBuffer.wrap("Knock\n".getBytes())); String response = readFromSocket(client); client.close(); assertEquals(response, "Knock Knock\n"); assertEquals(proxyServer.getNumConnects(), 1); } finally { proxyServer.stopServer(); tunnel.close(); assertFalse(tunnel.isTunnelThreadAlive()); } }
From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(timeOut = 15000) public void testTunnelToDelayedEchoServer() throws IOException { MockServer proxyServer = startConnectProxyServer(); Tunnel tunnel = Tunnel.build("localhost", delayedDoubleEchoServer.getServerSocketPort(), "localhost", proxyServer.getServerSocketPort()); try {/*w w w . j av a2 s . c o m*/ int tunnelPort = tunnel.getPort(); SocketChannel client = SocketChannel.open(); client.connect(new InetSocketAddress("localhost", tunnelPort)); client.write(ByteBuffer.wrap("Knock\n".getBytes())); String response = readFromSocket(client); client.close(); assertEquals(response, "Knock Knock\n"); assertEquals(proxyServer.getNumConnects(), 1); } finally { proxyServer.stopServer(); tunnel.close(); assertFalse(tunnel.isTunnelThreadAlive()); } }
From source file:org.apache.gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(enabled = false, timeOut = 15000) public void testTunnelToEchoServer() throws IOException { MockServer proxyServer = startConnectProxyServer(); Tunnel tunnel = Tunnel.build("localhost", doubleEchoServer.getServerSocketPort(), "localhost", proxyServer.getServerSocketPort()); try {/*from w w w . ja v a 2s . com*/ int tunnelPort = tunnel.getPort(); SocketChannel client = SocketChannel.open(); client.connect(new InetSocketAddress("localhost", tunnelPort)); client.write(ByteBuffer.wrap("Knock\n".getBytes())); String response = readFromSocket(client); client.close(); assertEquals(response, "Knock Knock\n"); assertEquals(proxyServer.getNumConnects(), 1); } finally { proxyServer.stopServer(); tunnel.close(); assertFalse(tunnel.isTunnelThreadAlive()); } }
From source file:org.apache.gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(enabled = false, timeOut = 15000) public void testTunnelToDelayedEchoServer() throws IOException { MockServer proxyServer = startConnectProxyServer(); Tunnel tunnel = Tunnel.build("localhost", delayedDoubleEchoServer.getServerSocketPort(), "localhost", proxyServer.getServerSocketPort()); try {//from w w w . j a v a 2 s . c o m int tunnelPort = tunnel.getPort(); SocketChannel client = SocketChannel.open(); client.connect(new InetSocketAddress("localhost", tunnelPort)); client.write(ByteBuffer.wrap("Knock\n".getBytes())); String response = readFromSocket(client); client.close(); assertEquals(response, "Knock Knock\n"); assertEquals(proxyServer.getNumConnects(), 1); } finally { proxyServer.stopServer(); tunnel.close(); assertFalse(tunnel.isTunnelThreadAlive()); } }
From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(timeOut = 15000) public void testTunnelToEchoServerMultiRequest() throws IOException { MockServer proxyServer = startConnectProxyServer(); Tunnel tunnel = Tunnel.build("localhost", doubleEchoServer.getServerSocketPort(), "localhost", proxyServer.getServerSocketPort()); try {/* w w w. j a v a2s . co m*/ int tunnelPort = tunnel.getPort(); SocketChannel client = SocketChannel.open(); client.connect(new InetSocketAddress("localhost", tunnelPort)); client.write(ByteBuffer.wrap("Knock\n".getBytes())); String response1 = readFromSocket(client); client.write(ByteBuffer.wrap("Hello\n".getBytes())); String response2 = readFromSocket(client); client.close(); assertEquals(response1, "Knock Knock\n"); assertEquals(response2, "Hello Hello\n"); assertEquals(proxyServer.getNumConnects(), 1); } finally { proxyServer.stopServer(); tunnel.close(); assertFalse(tunnel.isTunnelThreadAlive()); } }
From source file:org.apache.gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(enabled = false, timeOut = 15000) public void testTunnelToEchoServerMultiRequest() throws IOException { MockServer proxyServer = startConnectProxyServer(); Tunnel tunnel = Tunnel.build("localhost", doubleEchoServer.getServerSocketPort(), "localhost", proxyServer.getServerSocketPort()); try {//from w w w .java2s . c o m int tunnelPort = tunnel.getPort(); SocketChannel client = SocketChannel.open(); client.connect(new InetSocketAddress("localhost", tunnelPort)); client.write(ByteBuffer.wrap("Knock\n".getBytes())); String response1 = readFromSocket(client); client.write(ByteBuffer.wrap("Hello\n".getBytes())); String response2 = readFromSocket(client); client.close(); assertEquals(response1, "Knock Knock\n"); assertEquals(response2, "Hello Hello\n"); assertEquals(proxyServer.getNumConnects(), 1); } finally { proxyServer.stopServer(); tunnel.close(); assertFalse(tunnel.isTunnelThreadAlive()); } }
From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java
@Test(timeOut = 15000, expectedExceptions = IOException.class) public void testTunnelThreadDeadAfterUnexpectedException() throws IOException, InterruptedException { MockServer proxyServer = startConnectProxyServer(false, false, 8); Tunnel tunnel = Tunnel.build("localhost", doubleEchoServer.getServerSocketPort(), "localhost", proxyServer.getServerSocketPort()); String response = ""; try {//from w ww . j av a2 s . co m int tunnelPort = tunnel.getPort(); SocketChannel client = SocketChannel.open(); client.connect(new InetSocketAddress("localhost", tunnelPort)); client.write(ByteBuffer.wrap("Knock\n".getBytes())); response = readFromSocket(client); LOG.info(response); for (int i = 0; i < 5; i++) { client.write(ByteBuffer.wrap("Hello\n".getBytes())); Thread.sleep(100); } client.close(); } finally { proxyServer.stopServer(); tunnel.close(); assertNotEquals(response, "Knock Knock\n"); assertEquals(proxyServer.getNumConnects(), 1); assertFalse(tunnel.isTunnelThreadAlive()); } }