List of usage examples for java.nio.channels SelectionKey OP_CONNECT
int OP_CONNECT
To view the source code for java.nio.channels SelectionKey OP_CONNECT.
Click Source Link
From source file:GetWebPageApp.java
public static void main(String args[]) throws Exception { String resource, host, file;/*from w w w . j ava 2 s .c o m*/ int slashPos; resource = "www.java2s.com/index.htm"; // skip HTTP:// slashPos = resource.indexOf('/'); // find host/file separator if (slashPos < 0) { resource = resource + "/"; slashPos = resource.indexOf('/'); } file = resource.substring(slashPos); // isolate host and file parts host = resource.substring(0, slashPos); System.out.println("Host to contact: '" + host + "'"); System.out.println("File to fetch : '" + file + "'"); SocketChannel channel = null; try { Charset charset = Charset.forName("ISO-8859-1"); CharsetDecoder decoder = charset.newDecoder(); CharsetEncoder encoder = charset.newEncoder(); ByteBuffer buffer = ByteBuffer.allocateDirect(1024); CharBuffer charBuffer = CharBuffer.allocate(1024); InetSocketAddress socketAddress = new InetSocketAddress(host, 80); channel = SocketChannel.open(); channel.configureBlocking(false); channel.connect(socketAddress); selector = Selector.open(); channel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ); while (selector.select(500) > 0) { Set readyKeys = selector.selectedKeys(); try { Iterator readyItor = readyKeys.iterator(); while (readyItor.hasNext()) { SelectionKey key = (SelectionKey) readyItor.next(); readyItor.remove(); SocketChannel keyChannel = (SocketChannel) key.channel(); if (key.isConnectable()) { if (keyChannel.isConnectionPending()) { keyChannel.finishConnect(); } String request = "GET " + file + " \r\n\r\n"; keyChannel.write(encoder.encode(CharBuffer.wrap(request))); } else if (key.isReadable()) { keyChannel.read(buffer); buffer.flip(); decoder.decode(buffer, charBuffer, false); charBuffer.flip(); System.out.print(charBuffer); buffer.clear(); charBuffer.clear(); } else { System.err.println("Unknown key"); } } } catch (ConcurrentModificationException e) { } } } catch (UnknownHostException e) { System.err.println(e); } catch (IOException e) { System.err.println(e); } finally { if (channel != null) { try { channel.close(); } catch (IOException ignored) { } } } System.out.println("\nDone."); }
From source file:Main.java
public static void main(String[] args) throws Exception { InetAddress serverIPAddress = InetAddress.getByName("localhost"); int port = 19000; InetSocketAddress serverAddress = new InetSocketAddress(serverIPAddress, port); Selector selector = Selector.open(); SocketChannel channel = SocketChannel.open(); channel.configureBlocking(false);// www . jav a 2 s .c o m channel.connect(serverAddress); int operations = SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE; channel.register(selector, operations); userInputReader = new BufferedReader(new InputStreamReader(System.in)); while (true) { if (selector.select() > 0) { boolean doneStatus = processReadySet(selector.selectedKeys()); if (doneStatus) { break; } } } channel.close(); }
From source file:org.apache.axis2.transport.nhttp.LoggingIOSession.java
private static String formatOps(int ops) { StringBuffer buffer = new StringBuffer(6); buffer.append('['); if ((ops & SelectionKey.OP_READ) > 0) { buffer.append('r'); }/* www.j a v a 2 s . com*/ if ((ops & SelectionKey.OP_WRITE) > 0) { buffer.append('w'); } if ((ops & SelectionKey.OP_ACCEPT) > 0) { buffer.append('a'); } if ((ops & SelectionKey.OP_CONNECT) > 0) { buffer.append('c'); } buffer.append(']'); return buffer.toString(); }
From source file:me.xingrz.prox.tcp.tunnel.RemoteTunnel.java
public void connect(InetSocketAddress address) throws IOException { this.address = address; if (channel.connect(address)) { onConnectedInternal();//from w w w . jav a2 s .c o m } else { channel.register(selector, SelectionKey.OP_CONNECT, this); } }
From source file:com.ok2c.lightmtp.impl.protocol.LoggingIOSession.java
private static String formatOps(final int ops) { final StringBuilder buffer = new StringBuilder(6); buffer.append('['); if ((ops & SelectionKey.OP_READ) > 0) { buffer.append('r'); }/*from w w w. j a va 2s. c o m*/ if ((ops & SelectionKey.OP_WRITE) > 0) { buffer.append('w'); } if ((ops & SelectionKey.OP_ACCEPT) > 0) { buffer.append('a'); } if ((ops & SelectionKey.OP_CONNECT) > 0) { buffer.append('c'); } buffer.append(']'); return buffer.toString(); }
From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnectionThread.java
@Override public void run() { while (!isInterrupted()) { synchronized (this.pendingConnectionRequests) { if (!this.pendingConnectionRequests.isEmpty()) { final OutgoingConnection outgoingConnection = this.pendingConnectionRequests.poll(); try { final SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); final SelectionKey key = socketChannel.register(this.selector, SelectionKey.OP_CONNECT); socketChannel.connect(outgoingConnection.getConnectionAddress()); key.attach(outgoingConnection); } catch (final IOException ioe) { // IOException is reported by separate thread to avoid deadlocks final Runnable reporterThread = new Runnable() { @Override public void run() { outgoingConnection.reportConnectionProblem(ioe); }/*from w w w . ja v a 2 s. c om*/ }; new Thread(reporterThread).start(); } } } synchronized (this.pendingWriteEventSubscribeRequests) { if (!this.pendingWriteEventSubscribeRequests.isEmpty()) { final SelectionKey oldSelectionKey = this.pendingWriteEventSubscribeRequests.poll(); final OutgoingConnection outgoingConnection = (OutgoingConnection) oldSelectionKey.attachment(); final SocketChannel socketChannel = (SocketChannel) oldSelectionKey.channel(); try { final SelectionKey newSelectionKey = socketChannel.register(this.selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); newSelectionKey.attach(outgoingConnection); outgoingConnection.setSelectionKey(newSelectionKey); } catch (final IOException ioe) { // IOException is reported by separate thread to avoid deadlocks final Runnable reporterThread = new Runnable() { @Override public void run() { outgoingConnection.reportTransmissionProblem(ioe); } }; new Thread(reporterThread).start(); } } } synchronized (this.connectionsToClose) { final Iterator<Map.Entry<OutgoingConnection, Long>> closeIt = this.connectionsToClose.entrySet() .iterator(); final long now = System.currentTimeMillis(); while (closeIt.hasNext()) { final Map.Entry<OutgoingConnection, Long> entry = closeIt.next(); if ((entry.getValue().longValue() + MIN_IDLE_TIME_BEFORE_CLOSE) < now) { final OutgoingConnection outgoingConnection = entry.getKey(); closeIt.remove(); // Create new thread to close connection to avoid deadlocks final Runnable closeThread = new Runnable() { @Override public void run() { try { outgoingConnection.closeConnection(); } catch (IOException ioe) { outgoingConnection.reportTransmissionProblem(ioe); } } }; new Thread(closeThread).start(); } } } try { this.selector.select(10); } catch (IOException e) { LOG.error(e); } final Iterator<SelectionKey> iter = this.selector.selectedKeys().iterator(); while (iter.hasNext()) { final SelectionKey key = iter.next(); iter.remove(); if (key.isValid()) { if (key.isConnectable()) { doConnect(key); } else { if (key.isReadable()) { doRead(key); // A read will always result in an exception, so the write key will not be valid anymore continue; } if (key.isWritable()) { doWrite(key); } } } else { LOG.error("Received invalid key: " + key); } } } // Finally, try to close the selector try { this.selector.close(); } catch (IOException ioe) { LOG.debug(StringUtils.stringifyException(ioe)); } }
From source file:edu.tsinghua.lumaqq.qq.net.Porter.java
/** * portporter//from ww w. j a va 2s . c o m * * @param port * IPort * @throws ClosedChannelException * */ public void register(IPort port) throws ClosedChannelException { SelectableChannel channel = port.channel(); if (channel instanceof SocketChannel) channel.register(selector, SelectionKey.OP_CONNECT, port.getNIOHandler()); else if (channel instanceof DatagramChannel) channel.register(selector, SelectionKey.OP_READ, port.getNIOHandler()); if (!ports.contains(port)) ports.add(port); }
From source file:com.byteatebit.nbserver.simple.client.SimpleNbClient.java
public void tcpConnect(String remoteHost, int remotePort, IClientSocketChannelHandler socketChannelHandler, long timeout) throws IOException { if (!initialized.get()) throw new IllegalStateException("SimpleNbClient must first be initialized via init()"); SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); InetSocketAddress address = new InetSocketAddress(remoteHost, remotePort); INbContext nbContext = new NbContext(simpleNbService.getSelectorRegistrarBalancer().getSelectorRegistrar(), simpleNbService.getScheduler()); IOTask connectTask = (selectionKey) -> { boolean connectionFinished = false; try {//from ww w.j av a 2s . c o m connectionFinished = socketChannel.finishConnect(); } catch (IOException e) { LOG.error("Could not complete socket connection.", e); } if (!connectionFinished) { LOG.error("Could not complete socket connection. Closing socket channel"); selectionKey.cancel(); IOUtils.closeQuietly(socketChannel); socketChannelHandler.connectFailed(remoteHost, remotePort); return; } selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_CONNECT); socketChannelHandler.accept(nbContext, socketChannel); }; IOTimeoutTask timeoutTask = (selectionKey, ops) -> { LOG.error("Connect attempt timed out after " + timeout + " ms"); selectionKey.cancel(); IOUtils.closeQuietly(socketChannel); socketChannelHandler.connectFailed(remoteHost, remotePort); }; nbContext.register(socketChannel, SelectionKey.OP_CONNECT, connectTask, timeoutTask, timeout); socketChannel.connect(address); }
From source file:com.alibaba.napoli.gecko.core.nio.impl.SelectorManager.java
/** * channel//w w w .j ava2 s . c om * * @param channel * @param ops * @param attachment * @return */ public final Reactor registerChannel(final SelectableChannel channel, final int ops, final Object attachment) { this.awaitReady(); int index = 0; // Accept?Reactor if (ops == SelectionKey.OP_ACCEPT || ops == SelectionKey.OP_CONNECT) { index = 0; } else { if (this.dividend > 0) { index = this.sets.incrementAndGet() % this.dividend + 1; } else { index = 0; } } final Reactor reactor = this.reactorSet[index]; reactor.registerChannel(channel, ops, attachment); return reactor; }
From source file:com.taobao.gecko.core.nio.impl.SelectorManager.java
/** * channel/*w w w. ja v a 2 s . c o m*/ * * @param channel * @param ops * @param attachment * @return */ public final Reactor registerChannel(final SelectableChannel channel, final int ops, final Object attachment) { this.awaitReady(); int index = 0; // AcceptReactor if (ops == SelectionKey.OP_ACCEPT || ops == SelectionKey.OP_CONNECT) { index = 0; } else { if (this.dividend > 0) { index = this.sets.incrementAndGet() % this.dividend + 1; } else { index = 0; } } final Reactor reactor = this.reactorSet[index]; reactor.registerChannel(channel, ops, attachment); return reactor; }