List of usage examples for java.nio.channels SocketChannel configureBlocking
public final SelectableChannel configureBlocking(boolean block) throws IOException
From source file:gridool.util.net.PoolableSocketChannelFactory.java
private static SocketChannel createSocketChannel(final SocketAddress sockAddr, final boolean blocking, final int rcvbufSize) { final SocketChannel ch; try {//from w w w. j av a 2s .c o m ch = SocketChannel.open(); ch.configureBlocking(blocking); } catch (IOException e) { LOG.error("Failed to open SocketChannel.", e); throw new IllegalStateException(e); } final Socket sock = ch.socket(); if (rcvbufSize != -1) { try { sock.setReceiveBufferSize(rcvbufSize); } catch (SocketException e) { LOG.error("Failed to setReceiveBufferSize.", e); throw new IllegalStateException(e); } } try { ch.connect(sockAddr); } catch (IOException e) { LOG.error("Failed to connect socket: " + sockAddr, e); throw new IllegalStateException(e); } return ch; }
From source file:gridool.communication.transport.nio.GridNioServer.java
private static void handleAccept(final ServerSocketChannel serverChannel, final Selector selector) throws IOException { final SocketChannel channel = serverChannel.accept(); if (channel == null) { return;//ww w . j a va 2s.c o m } channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ, new GridMessageBuffer()); if (LOG.isDebugEnabled()) { LOG.debug("Accepted a new client connection: " + channel.socket().getRemoteSocketAddress()); } }
From source file:com.github.neoio.nio.util.NIOUtils.java
public static SocketChannel openClientSocket(Selector selector, SocketAddress endPointAddress) throws NetSocketException { SocketChannel toReturn; try {/* ww w . j a v a2 s.c o m*/ toReturn = SocketChannel.open(endPointAddress); toReturn.configureBlocking(false); toReturn.register(selector, SelectionKey.OP_READ); } catch (IOException e) { logger.error("IOException occurred while opening client socket", e); toReturn = null; } return toReturn; }
From source file:com.buaa.cfs.net.SocketIOWithTimeout.java
/** * The contract is similar to {@link SocketChannel#connect(SocketAddress)} with a timeout. * * @param channel - this should be a {@link SelectableChannel} * @param endpoint/*from ww w .ja va 2 s . co m*/ * * @throws IOException * @see SocketChannel#connect(SocketAddress) */ static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException { boolean blockingOn = channel.isBlocking(); if (blockingOn) { channel.configureBlocking(false); } try { if (channel.connect(endpoint)) { return; } long timeoutLeft = timeout; long endTime = (timeout > 0) ? (Time.now() + timeout) : 0; while (true) { // we might have to call finishConnect() more than once // for some channels (with user level protocols) int ret = selector.select((SelectableChannel) channel, SelectionKey.OP_CONNECT, timeoutLeft); if (ret > 0 && channel.finishConnect()) { return; } if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - Time.now())) <= 0)) { throw new SocketTimeoutException( timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT)); } } } catch (IOException e) { // javadoc for SocketChannel.connect() says channel should be closed. try { channel.close(); } catch (IOException ignored) { } throw e; } finally { if (blockingOn && channel.isOpen()) { channel.configureBlocking(true); } } }
From source file:eu.stratosphere.nephele.net.SocketIOWithTimeout.java
/** * The contract is similar to {@link SocketChannel#connect(SocketAddress)} with a timeout. * /* www .j a va2 s.c o m*/ * @see SocketChannel#connect(SocketAddress) * @param channel * - this should be a {@link SelectableChannel} * @param endpoint * @throws IOException */ static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException { boolean blockingOn = channel.isBlocking(); if (blockingOn) { channel.configureBlocking(false); } try { if (channel.connect(endpoint)) { return; } long timeoutLeft = timeout; long endTime = (timeout > 0) ? (System.currentTimeMillis() + timeout) : 0; while (true) { // we might have to call finishConnect() more than once // for some channels (with user level protocols) int ret = selector.select((SelectableChannel) channel, SelectionKey.OP_CONNECT, timeoutLeft); if (ret > 0 && channel.finishConnect()) { return; } if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - System.currentTimeMillis())) <= 0)) { throw new SocketTimeoutException( timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT)); } } } catch (IOException e) { // javadoc for SocketChannel.connect() says channel should be closed. try { channel.close(); } catch (IOException ignored) { } throw e; } finally { if (blockingOn && channel.isOpen()) { channel.configureBlocking(true); } } }
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 w w w .ja v a2 s . c om*/ 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:gridool.communication.transport.tcp.GridNonBlockingClient.java
public void sendMessage(SocketAddress sockAddr, GridCommunicationMessage msg) throws GridException { final SocketChannel channel; try {//from ww w. j ava2 s.c om channel = SocketChannel.open(); channel.configureBlocking(false); } catch (IOException e) { LOG.error(PrintUtils.prettyPrintStackTrace(e, -1)); throw new GridException(e); } final Socket socket = channel.socket(); try { socket.connect(sockAddr); // wait for connect succeeds while (!channel.finishConnect()) { try { Thread.sleep(1000L); } catch (InterruptedException e) { ; } } } catch (IOException e) { IOUtils.closeQuietly(channel); NetUtils.closeQuietly(socket); LOG.error(PrintUtils.prettyPrintStackTrace(e, -1)); throw new GridException(e); } final ByteBuffer buf = toBuffer(msg); if (LOG.isDebugEnabled()) { LOG.debug("Sending a GridCommunicationMessage [" + msg.getMessageId() + " (" + buf.remaining() + " bytes)] to a node [" + sockAddr + "] using a channel [" + channel + ']'); } final int written; try { written = NIOUtils.countingWriteFully(channel, buf); NetUtils.shutdownOutputQuietly(socket); // terminate socket output (send FIN) } catch (IOException ioe) { final String errmsg = "Failed to send a GridCommunicationMessage [" + msg + "] to host [" + sockAddr + ']'; LOG.error(errmsg, ioe); throw new GridException(errmsg, ioe); } catch (Throwable e) { LOG.fatal(e.getMessage(), e); throw new GridException("Unexpected exception was caused", e); } finally { NetUtils.closeQuietly(socket); } if (LOG.isDebugEnabled()) { LOG.debug("Succeeded to send a GridCommunicationMessage (" + written + " bytes) to host [" + sockAddr + "]"); } }
From source file:idgs.client.TcpClient.java
private void processRead(SelectionKey key) throws IOException { log.debug("-------------begin to process read-----------"); SocketChannel channel = (SocketChannel) key.channel(); channel.configureBlocking(false); handler.onRead(channel);//ww w .ja v a2 s . c o m log.debug("-------------end to process read-----------"); }
From source file:com.l2jfree.network.mmocore.AcceptorThread.java
private void acceptConnection(SelectionKey key) { SocketChannel sc; try {//from w w w .jav a 2 s .co m while ((sc = ((ServerSocketChannel) key.channel()).accept()) != null) { if (getMMOController().acceptConnectionFrom(sc)) { sc.configureBlocking(false); Util.printSection(getMMOController().getClass().getSimpleName() + " " + sc.socket().getRemoteSocketAddress().toString()); final T con = getMMOController().createClient(sc); con.enableReadInterest(); } else { IOUtils.closeQuietly(sc.socket()); } } } catch (IOException e) { e.printStackTrace(); } }
From source file:ee.ria.xroad.proxy.clientproxy.FastestSocketSelector.java
private SocketInfo initConnections(Selector selector) throws IOException { log.trace("initConnections()"); for (URI target : addresses) { SocketChannel channel = SocketChannel.open(); channel.setOption(StandardSocketOptions.TCP_NODELAY, true); channel.configureBlocking(false); try {// ww w .j a va2 s .c om channel.register(selector, SelectionKey.OP_CONNECT, target); if (channel.connect(new InetSocketAddress(target.getHost(), target.getPort()))) { // connected immediately channel.configureBlocking(true); return new SocketInfo(target, channel.socket()); } } catch (Exception e) { closeQuietly(channel); log.trace("Error connecting to '{}': {}", target, e); } } return null; }