use of java.nio.channels.ServerSocketChannel in project ignite by apache.
the class FileDownloader method download.
/**
*/
public void download(GridFutureAdapter<?> fut) {
this.finishFut = fut;
final ServerSocketChannel ch = serverChannel;
fut.listen(new IgniteInClosureX<IgniteInternalFuture<?>>() {
@Override
public void applyx(IgniteInternalFuture<?> future) throws IgniteCheckedException {
try {
if (log != null && log.isInfoEnabled())
log.info("Server socket closed " + ch.getLocalAddress());
ch.close();
} catch (Exception ex) {
U.error(log, "Fail close socket.", ex);
throw new IgniteCheckedException(ex);
}
}
});
FileChannel writeChannel = null;
SocketChannel readChannel = null;
try {
File f = new File(path.toUri().getPath());
if (f.exists())
f.delete();
File cacheWorkDir = f.getParentFile();
if (!cacheWorkDir.exists())
cacheWorkDir.mkdir();
writeChannel = FileChannel.open(path, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
initFut.onDone();
readChannel = serverChannel.accept();
long pos = 0;
long size = this.size.get();
while (size == -1 || pos < size) {
pos += writeChannel.transferFrom(readChannel, pos, CHUNK_SIZE);
if (size == -1)
size = this.size.get();
}
} catch (IOException ex) {
initFut.onDone(ex);
fut.onDone(ex);
} finally {
try {
if (writeChannel != null)
writeChannel.close();
} catch (IOException ex) {
throw new IgniteException("Could not close file: " + path);
}
try {
if (readChannel != null)
readChannel.close();
} catch (IOException ex) {
throw new IgniteException("Could not close socket");
}
}
}
use of java.nio.channels.ServerSocketChannel in project ambry by linkedin.
the class Processor method acceptConnection.
protected SocketChannel acceptConnection(SelectionKey key) throws SocketException, IOException {
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
serverSocketChannel.socket().setReceiveBufferSize(recvBufferSize);
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.socket().setTcpNoDelay(true);
socketChannel.socket().setSendBufferSize(sendBufferSize);
logger.trace("Accepted connection from {} on {}. sendBufferSize " + "[actual|requested]: [{}|{}] recvBufferSize [actual|requested]: [{}|{}]", socketChannel.socket().getInetAddress(), socketChannel.socket().getLocalSocketAddress(), socketChannel.socket().getSendBufferSize(), sendBufferSize, socketChannel.socket().getReceiveBufferSize(), recvBufferSize);
return socketChannel;
}
use of java.nio.channels.ServerSocketChannel in project ambry by linkedin.
the class Processor method openServerSocket.
/*
* Create a server socket to listen for connections on.
*/
private ServerSocketChannel openServerSocket(int port) throws IOException {
InetSocketAddress address = new InetSocketAddress(port);
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
serverChannel.socket().bind(address);
logger.info("Awaiting socket connections on {}:{}", address.getHostName(), port);
return serverChannel;
}
use of java.nio.channels.ServerSocketChannel in project nifi by apache.
the class SocketChannelDispatcher method run.
@Override
public void run() {
while (!stopped) {
try {
int selected = selector.select();
// if stopped the selector could already be closed which would result in a ClosedSelectorException
if (selected > 0 && !stopped) {
Iterator<SelectionKey> selectorKeys = selector.selectedKeys().iterator();
// if stopped we don't want to modify the keys because close() may still be in progress
while (selectorKeys.hasNext() && !stopped) {
SelectionKey key = selectorKeys.next();
selectorKeys.remove();
if (!key.isValid()) {
continue;
}
if (key.isAcceptable()) {
// Handle new connections coming in
final ServerSocketChannel channel = (ServerSocketChannel) key.channel();
final SocketChannel socketChannel = channel.accept();
// Check for available connections
if (currentConnections.incrementAndGet() > maxConnections) {
currentConnections.decrementAndGet();
logger.warn("Rejecting connection from {} because max connections has been met", new Object[] { socketChannel.getRemoteAddress().toString() });
IOUtils.closeQuietly(socketChannel);
continue;
}
logger.debug("Accepted incoming connection from {}", new Object[] { socketChannel.getRemoteAddress().toString() });
// Set socket to non-blocking, and register with selector
socketChannel.configureBlocking(false);
SelectionKey readKey = socketChannel.register(selector, SelectionKey.OP_READ);
// Prepare the byte buffer for the reads, clear it out
ByteBuffer buffer = bufferPool.poll();
buffer.clear();
buffer.mark();
// If we have an SSLContext then create an SSLEngine for the channel
SSLSocketChannel sslSocketChannel = null;
if (sslContext != null) {
final SSLEngine sslEngine = sslContext.createSSLEngine();
sslEngine.setUseClientMode(false);
switch(clientAuth) {
case REQUIRED:
sslEngine.setNeedClientAuth(true);
break;
case WANT:
sslEngine.setWantClientAuth(true);
break;
case NONE:
sslEngine.setNeedClientAuth(false);
sslEngine.setWantClientAuth(false);
break;
}
sslSocketChannel = new SSLSocketChannel(sslEngine, socketChannel);
}
// Attach the buffer and SSLSocketChannel to the key
SocketChannelAttachment attachment = new SocketChannelAttachment(buffer, sslSocketChannel);
readKey.attach(attachment);
} else if (key.isReadable()) {
// Clear out the operations the select is interested in until done reading
key.interestOps(0);
// Create a handler based on the protocol and whether an SSLEngine was provided or not
final Runnable handler;
if (sslContext != null) {
handler = handlerFactory.createSSLHandler(key, this, charset, eventFactory, events, logger);
} else {
handler = handlerFactory.createHandler(key, this, charset, eventFactory, events, logger);
}
// run the handler
executor.execute(handler);
}
}
}
// Add back all idle sockets to the select
SelectionKey key;
while ((key = keyQueue.poll()) != null) {
key.interestOps(SelectionKey.OP_READ);
}
} catch (IOException e) {
logger.error("Error accepting connection from SocketChannel", e);
}
}
}
use of java.nio.channels.ServerSocketChannel in project nifi by apache.
the class SocketChannelDispatcher method open.
@Override
public void open(final InetAddress nicAddress, final int port, final int maxBufferSize) throws IOException {
stopped = false;
executor = Executors.newFixedThreadPool(maxConnections);
final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
if (maxBufferSize > 0) {
serverSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, maxBufferSize);
final int actualReceiveBufSize = serverSocketChannel.getOption(StandardSocketOptions.SO_RCVBUF);
if (actualReceiveBufSize < maxBufferSize) {
logger.warn("Attempted to set Socket Buffer Size to " + maxBufferSize + " bytes but could only set to " + actualReceiveBufSize + "bytes. You may want to consider changing the Operating System's " + "maximum receive buffer");
}
}
serverSocketChannel.socket().bind(new InetSocketAddress(nicAddress, port));
selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
Aggregations