List of usage examples for java.nio.channels SocketChannel configureBlocking
public final SelectableChannel configureBlocking(boolean block) throws IOException
From source file:voldemort.server.niosocket.NioSelectorManager.java
@Override protected void processEvents() { try {//from ww w . j a v a 2 s . c o m SocketChannel socketChannel = null; while ((socketChannel = socketChannelQueue.poll()) != null) { if (isClosed.get()) { if (logger.isInfoEnabled()) logger.debug("Closed, exiting for " + endpoint); break; } try { if (logger.isDebugEnabled()) logger.debug("Registering connection from " + socketChannel.socket().getPort()); socketChannel.socket().setTcpNoDelay(true); socketChannel.socket().setReuseAddress(true); socketChannel.socket().setSendBufferSize(socketBufferSize); if (socketChannel.socket().getReceiveBufferSize() != this.socketBufferSize) if (logger.isDebugEnabled()) logger.debug("Requested socket receive buffer size was " + this.socketBufferSize + " bytes but actual size is " + socketChannel.socket().getReceiveBufferSize() + " bytes."); if (socketChannel.socket().getSendBufferSize() != this.socketBufferSize) if (logger.isDebugEnabled()) logger.debug("Requested socket send buffer size was " + this.socketBufferSize + " bytes but actual size is " + socketChannel.socket().getSendBufferSize() + " bytes."); socketChannel.configureBlocking(false); AsyncRequestHandler attachment = new AsyncRequestHandler(selector, socketChannel, requestHandlerFactory, socketBufferSize, numActiveConnections); if (!isClosed.get()) { socketChannel.register(selector, SelectionKey.OP_READ, attachment); numActiveConnections.increment(); } } catch (ClosedSelectorException e) { if (logger.isDebugEnabled()) logger.debug("Selector is closed, exiting"); close(); break; } catch (Exception e) { if (logger.isEnabledFor(Level.ERROR)) logger.error(e.getMessage(), e); } } } catch (Exception e) { if (logger.isEnabledFor(Level.ERROR)) logger.error(e.getMessage(), e); } }
From source file:x10.x10rt.yarn.ApplicationMaster.java
protected void handleX10() { // handle X10 place requests Iterator<SelectionKey> events = null; while (running) { try {/*from w w w . j av a 2 s . c om*/ SelectionKey key; // check for previously unhandled events if (events != null && events.hasNext()) { key = events.next(); events.remove(); } else if (selector.select() == 0) // check for new events continue; // nothing to process, go back and block on select again else { // select returned some events events = selector.selectedKeys().iterator(); key = events.next(); events.remove(); } // process the selectionkey if (key.isAcceptable()) { LOG.info("New connection from X10 detected"); // accept any connections on the server socket, and look for things to read from it ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); } if (key.isReadable()) { SocketChannel sc = (SocketChannel) key.channel(); ByteBuffer incomingMsg; if (pendingReads.containsKey(sc)) incomingMsg = pendingReads.remove(sc); else incomingMsg = ByteBuffer.allocateDirect(headerLength).order(ByteOrder.nativeOrder()); LOG.info("Reading message from X10"); try { if (sc.read(incomingMsg) == -1) { // socket closed sc.close(); key.cancel(); pendingReads.remove(sc); } else if (incomingMsg.hasRemaining()) { LOG.info("Message header partially read. " + incomingMsg.remaining() + " bytes remaining"); pendingReads.put(sc, incomingMsg); } else { // buffer is full if (incomingMsg.capacity() == headerLength) { // check to see if there is a body associated with this message header int datalen = incomingMsg.getInt(headerLength - 4); //System.err.println("Byte order is "+incomingMsg.order()+" datalen="+datalen); if (datalen == 0) processMessage(incomingMsg, sc); else { // create a larger array to hold the header+body ByteBuffer newBuffer = ByteBuffer.allocateDirect(headerLength + datalen) .order(ByteOrder.nativeOrder()); incomingMsg.rewind(); newBuffer.put(incomingMsg); incomingMsg = newBuffer; sc.read(incomingMsg); // read in the body, if available if (incomingMsg.hasRemaining()) { LOG.info("Message partially read. " + incomingMsg.remaining() + " bytes remaining"); pendingReads.put(sc, incomingMsg); } else processMessage(incomingMsg, sc); } } } } catch (IOException e) { LOG.warn("Error reading in message from socket channel", e); } } } catch (IOException e) { LOG.warn("Error handling X10 links", e); } } }
From source file:xbird.util.net.PoolableSocketChannelFactory.java
private static SocketChannel createSocketChannel(final SocketAddress sockAddr, final boolean blocking, final int rcvbufSize) { final SocketChannel ch; try {/*ww 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); } } final boolean connected; try { connected = ch.connect(sockAddr); } catch (IOException e) { LOG.error("Failed to connect socket: " + sockAddr, e); throw new IllegalStateException(e); } if (!connected) { throw new IllegalStateException("Failed to connect: " + sockAddr); } return ch; }
From source file:xbird.util.xfer.RecievedFileWriter.java
public final void handleRequest(@Nonnull final SocketChannel inChannel, @Nonnull final Socket socket) throws IOException { final StopWatch sw = new StopWatch(); if (!inChannel.isBlocking()) { inChannel.configureBlocking(true); }//w ww . j a v a2s .co m InputStream in = socket.getInputStream(); DataInputStream dis = new DataInputStream(in); String fname = IOUtils.readString(dis); String dirPath = IOUtils.readString(dis); long len = dis.readLong(); boolean append = dis.readBoolean(); boolean ackRequired = dis.readBoolean(); boolean hasAdditionalHeader = dis.readBoolean(); if (hasAdditionalHeader) { readAdditionalHeader(dis, fname, dirPath, len, append, ackRequired); } final File file; if (dirPath == null) { file = new File(baseDir, fname); } else { File dir = FileUtils.resolvePath(baseDir, dirPath); file = new File(dir, fname); } preFileAppend(file, append); final FileOutputStream dst = new FileOutputStream(file, append); final String fp = file.getAbsolutePath(); final ReadWriteLock filelock = accquireLock(fp, locks); final FileChannel fileCh = dst.getChannel(); final long startPos = file.length(); try { NIOUtils.transferFullyFrom(inChannel, 0, len, fileCh); // REVIEWME really an atomic operation? } finally { IOUtils.closeQuietly(fileCh, dst); releaseLock(fp, filelock, locks); postFileAppend(file, startPos, len); } if (ackRequired) { OutputStream out = socket.getOutputStream(); DataOutputStream dos = new DataOutputStream(out); dos.writeLong(len); postAck(file, startPos, len); } if (LOG.isDebugEnabled()) { SocketAddress remoteAddr = socket.getRemoteSocketAddress(); LOG.debug("Received a " + (append ? "part of file '" : "file '") + file.getAbsolutePath() + "' of " + len + " bytes from " + remoteAddr + " in " + sw.toString()); } }