List of usage examples for java.nio.channels SocketChannel open
public static SocketChannel open() throws IOException
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 {/* www. ja v a 2 s . 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:gridool.util.xfer.TransferUtils.java
public static void send(@Nonnull final FastByteArrayOutputStream data, @Nonnull final String fileName, @Nullable final String writeDirPath, @Nonnull final InetAddress dstAddr, final int dstPort, final boolean append, final boolean sync, @Nullable final TransferClientHandler handler) throws IOException { final SocketAddress dstSockAddr = new InetSocketAddress(dstAddr, dstPort); SocketChannel channel = null; Socket socket = null;//from ww w. ja v a 2s . co m final OutputStream out; try { channel = SocketChannel.open(); socket = channel.socket(); socket.connect(dstSockAddr); out = socket.getOutputStream(); } catch (IOException e) { LOG.error("failed to connect: " + dstSockAddr, e); IOUtils.closeQuietly(channel); NetUtils.closeQuietly(socket); throw e; } DataInputStream din = null; if (sync) { InputStream in = socket.getInputStream(); din = new DataInputStream(in); } final DataOutputStream dos = new DataOutputStream(out); final StopWatch sw = new StopWatch(); try { IOUtils.writeString(fileName, dos); IOUtils.writeString(writeDirPath, dos); long nbytes = data.size(); dos.writeLong(nbytes); dos.writeBoolean(append); dos.writeBoolean(sync); if (handler == null) { dos.writeBoolean(false); } else { dos.writeBoolean(true); handler.writeAdditionalHeader(dos); } // send file using zero-copy send data.writeTo(out); if (LOG.isDebugEnabled()) { LOG.debug("Sent a file data '" + fileName + "' of " + nbytes + " bytes to " + dstSockAddr.toString() + " in " + sw.toString()); } if (sync) {// receive ack in sync mode long remoteRecieved = din.readLong(); if (remoteRecieved != nbytes) { throw new IllegalStateException( "Sent " + nbytes + " bytes, but remote node received " + remoteRecieved + " bytes"); } } } catch (FileNotFoundException e) { LOG.error(PrintUtils.prettyPrintStackTrace(e, -1)); throw e; } catch (IOException e) { LOG.error(PrintUtils.prettyPrintStackTrace(e, -1)); throw e; } finally { IOUtils.closeQuietly(din, dos); IOUtils.closeQuietly(channel); NetUtils.closeQuietly(socket); } }
From source file:org.cloudata.core.commitlog.CommitLogClient.java
public void open() throws UnmatchedLogException, CommitLogInterruptedException, IOException { pipeKey = generateUniqueKey();/*from www.jav a2s .co m*/ if (LOG.isDebugEnabled()) { String msg = ""; for (String addr : ipAddressList) { msg = msg + addr + ", "; } LOG.debug("Open new pipe with timeout[" + this.timeout + "], key [" + pipeKey + "], -> " + msg); } String ret = null; Socket s = null; try { sc = SocketChannel.open(); s = sc.socket(); s.setTcpNoDelay(true); s.setSoTimeout(timeout); int addressIndex = 0; if (verifiedAddressIndex >= 0) { addressIndex = verifiedAddressIndex; } LOG.debug("open pipe to " + pipeAddressList[addressIndex]); sc.connect(pipeAddressList[addressIndex]); } catch (ClosedByInterruptException e) { internalClose(); throw new CommitLogInterruptedException(); } catch (IOException e) { throw new CommitLogShutDownException(e); } try { byte[] body = buildBody(); currentStream = new DataOutputStream(new BufferedOutputStream(s.getOutputStream(), 8192)); checkInputStream = new DataInputStream(s.getInputStream()); currentStream.write(MAGIC_KEY); currentStream.writeInt(0); currentStream.writeInt(body.length); currentStream.write(body); currentStream.flush(); DataInputStream dis = new DataInputStream(s.getInputStream()); byte[] key = new byte[MAGIC_KEY.length]; if (dis.read(key) < 0) { throw new IOException("Fail to establish pipe connection to " + getPipeAddressListStr()); } if (!Arrays.equals(MAGIC_KEY, key)) { throw new IOException( "Fail to establish pipe connection to " + getPipeAddressList() + "due to wrong magic key"); } int opCode = dis.readInt(); int replyLength = dis.readInt(); body = new byte[replyLength]; dis.read(body); ret = new String(body); } catch (ClosedByInterruptException e) { internalClose(); throw new CommitLogInterruptedException(); } catch (IOException e) { LOG.warn("Fail to establish pipe to " + getPipeAddressListStr() + " due to " + e, e); internalClose(); throw new IOException("Fail to establish pipe connection to " + getPipeAddressListStr(), e); } if (!ret.equals(Constants.PIPE_CONNECTED)) { internalClose(); if (ret.equals("Log files are unmatched among commit log servers")) { throw new UnmatchedLogException("Log files are unmatched among commit log servers"); } throw new IOException( "Fail to establish pipe connection to " + getPipeAddressListStr() + ". response : " + ret); } else { closed = false; } }
From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkClient.java
private boolean connect() { try {/*from ww w . j av a 2s . c o m*/ state.set(NetworkStateEnum.NETWORK_STATE_CONNECTING.value); socketChannel = SocketChannel.open(); // socketChannel.connect(new InetSocketAddress(hostName, port)); // ?? socketChannel.configureBlocking(false); selector = Selector.open(); socketChannel.register(selector, SelectionKey.OP_READ); opsChangeRequest = new SocketChannelOPSChangeRequest(socketChannel, 0); // state.set(NetworkStateEnum.NETWORK_STATE_CONNECTED.value); logger.warn(String.format("Slave connected to %s", hostName)); return true; } catch (IOException e) { logger.error("OOPSException", e); } state.set(NetworkStateEnum.NETWORK_STATE_DISCONNECT.value); return false; }
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 {//from www .j a v a 2 s . co 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:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpPacketTransport.java
/** * Connect the transport to its remote endpoint *///from w w w .j a v a 2s. co m private SocketChannel connect(URI transportURI) throws PacketTransportException { String host = transportURI.getHost(); int port = transportURI.getPort(); try { SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); SocketUtils.setupSocket(socketChannel.socket(), socketSendBufferSize, socketRecvBufferSize); log.debug("#" + id + " opening a TCP connection to " + host + ":" + port); socketChannel.connect(new InetSocketAddress(host, port)); return socketChannel; } catch (Exception e) { log.error("#" + id + " could not connect to " + host + ":" + port, e); throw new PacketTransportException("Could not connect to " + host + ":" + port + " : " + e.toString()); } }
From source file:org.openhab.io.transport.cul.internal.network.CULNetworkHandlerImpl.java
@Override public void run() { logger.info("event loop starting"); try {/*w w w . ja v a 2 s. c o m*/ while (!Thread.interrupted()) { // reconnection loop try { selector = Selector.open(); channel = SocketChannel.open(); configureChannel(channel); channel.connect(address); channel.register(selector, SelectionKey.OP_CONNECT); while (!thread.isInterrupted() && channel.isOpen()) { // events multiplexing loop if (selector.select() > 0) { processSelectedKeys(selector.selectedKeys()); } } } catch (Exception e) { logger.warn("exception", e); } finally { connected.set(false); onDisconnected(); writeBuf.clear(); readBuf.clear(); if (channel != null) { channel.close(); } if (selector != null) { selector.close(); } logger.info("connection closed"); } try { Thread.sleep(reconnectInterval); if (reconnectInterval < MAXIMUM_RECONNECT_INTERVAL) { reconnectInterval *= 2; } logger.info("reconnecting to {}", address); } catch (InterruptedException e) { break; } } } catch (Exception e) { logger.warn("unrecoverable error", e); } logger.info("event loop terminated"); }
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 va2s .co 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:com.alexkli.jhb.Worker.java
@Override public void run() { try {/*w ww.j av a 2 s.c om*/ 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: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 ww.java2 s . c om*/ 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()); } }