use of java.nio.channels.SelectionKey in project cobar by alibaba.
the class AbstractConnection method enableWrite.
/**
* 打开写事件
*/
private void enableWrite() {
final Lock lock = this.keyLock;
lock.lock();
try {
SelectionKey key = this.processKey;
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
} finally {
lock.unlock();
}
processKey.selector().wakeup();
}
use of java.nio.channels.SelectionKey in project cobar by alibaba.
the class AbstractConnection method disableRead.
/**
* 关闭读事件
*/
public void disableRead() {
final Lock lock = this.keyLock;
lock.lock();
try {
SelectionKey key = this.processKey;
key.interestOps(key.interestOps() & OP_NOT_READ);
} finally {
lock.unlock();
}
}
use of java.nio.channels.SelectionKey in project voldemort by voldemort.
the class AbstractSelectorManager method close.
public void close() {
// the punch...
if (!isClosed.compareAndSet(false, true))
return;
try {
for (SelectionKey sk : selector.keys()) {
try {
if (logger.isTraceEnabled())
logger.trace("Closing SelectionKey's channel");
sk.channel().close();
Object attachment = sk.attachment();
if (attachment instanceof Closeable) {
IOUtils.closeQuietly((Closeable) attachment);
}
} catch (Exception e) {
if (logger.isEnabledFor(Level.WARN))
logger.warn(e.getMessage(), e);
}
try {
if (logger.isTraceEnabled())
logger.trace("Cancelling SelectionKey");
sk.cancel();
} catch (Exception e) {
if (logger.isEnabledFor(Level.WARN))
logger.warn(e.getMessage(), e);
}
}
} catch (Exception e) {
if (logger.isEnabledFor(Level.WARN))
logger.warn(e.getMessage(), e);
}
try {
selector.close();
} catch (Exception e) {
if (logger.isEnabledFor(Level.WARN))
logger.warn(e.getMessage(), e);
}
}
use of java.nio.channels.SelectionKey in project voldemort by voldemort.
the class ClientRequestExecutor method addClientRequest.
public synchronized void addClientRequest(ClientRequest<?> clientRequest, long timeoutMs, long elapsedNs) {
if (logger.isTraceEnabled()) {
logger.trace("Associating client with " + socketChannel.socket());
}
this.clientRequest = clientRequest;
computeExpirationTime(timeoutMs, elapsedNs);
outputStream.getBuffer().clear();
boolean wasSuccessful = clientRequest.formatRequest(outputStream);
outputStream.getBuffer().flip();
if (wasSuccessful) {
SelectionKey selectionKey = socketChannel.keyFor(selector);
if (selectionKey != null) {
selectionKey.interestOps(SelectionKey.OP_WRITE);
// This wakeup is required because it's invoked by the calling
// code in a different thread than the SelectorManager.
selector.wakeup();
} else {
/*
* Servers could close the Socket during bounce or other
* situations. In those cases the cached client connections are
* cleared up as well. But there is a race condition between the
* requests getting cached connections and connections getting
* cleared up. In those cases a request could get a connection
* but before sending request, it could have been invalidated
* and removed from the selector. This place handles the case by
* sending an IO Error to the request.
*
* This case is no different than the request sent to the server
* and the server closing the socket.
*/
String message = "Client associated with " + socketChannel.socket() + " was not registered with Selector " + selector + ", it could have been closed due to server restarts ";
logger.warn(message);
IOException ex = new IOException(message);
reportException(ex);
completeClientRequest();
}
} else {
logger.warn("Client associated with " + socketChannel.socket() + " did not successfully buffer output for request");
completeClientRequest();
}
}
use of java.nio.channels.SelectionKey in project quorrabot by GloriousEggroll.
the class WebSocketServer method run.
// Runnable IMPLEMENTATION /////////////////////////////////////////////////
public void run() {
synchronized (this) {
if (selectorthread != null) {
throw new IllegalStateException(getClass().getName() + " can only be started once.");
}
selectorthread = Thread.currentThread();
if (isclosed.get()) {
return;
}
}
selectorthread.setName("WebsocketSelector" + selectorthread.getId());
try {
server = ServerSocketChannel.open();
server.configureBlocking(false);
ServerSocket socket = server.socket();
socket.setReceiveBufferSize(WebSocketImpl.RCVBUF);
socket.bind(address);
selector = Selector.open();
server.register(selector, server.validOps());
} catch (IOException ex) {
handleFatal(null, ex);
return;
}
try {
while (!selectorthread.isInterrupted()) {
SelectionKey key = null;
WebSocketImpl conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while (i.hasNext()) {
key = i.next();
if (!key.isValid()) {
// Object o = key.attachment();
continue;
}
if (key.isAcceptable()) {
if (!onConnect(key)) {
key.cancel();
continue;
}
SocketChannel channel = server.accept();
channel.configureBlocking(false);
WebSocketImpl w = wsf.createWebSocket(this, drafts, channel.socket());
w.key = channel.register(selector, SelectionKey.OP_READ, w);
w.channel = wsf.wrapChannel(channel, w.key);
i.remove();
allocateBuffers(w);
continue;
}
if (key.isReadable()) {
conn = (WebSocketImpl) key.attachment();
ByteBuffer buf = takeBuffer();
try {
if (SocketChannelIOHelper.read(buf, conn, conn.channel)) {
if (buf.hasRemaining()) {
conn.inQueue.put(buf);
queue(conn);
i.remove();
if (conn.channel instanceof WrappedByteChannel) {
if (((WrappedByteChannel) conn.channel).isNeedRead()) {
iqueue.add(conn);
}
}
} else {
pushBuffer(buf);
}
} else {
pushBuffer(buf);
}
} catch (IOException e) {
pushBuffer(buf);
throw e;
}
}
if (key.isWritable()) {
conn = (WebSocketImpl) key.attachment();
if (SocketChannelIOHelper.batch(conn, conn.channel)) {
if (key.isValid()) {
key.interestOps(SelectionKey.OP_READ);
}
}
}
}
while (!iqueue.isEmpty()) {
conn = iqueue.remove(0);
WrappedByteChannel c = ((WrappedByteChannel) conn.channel);
ByteBuffer buf = takeBuffer();
try {
if (SocketChannelIOHelper.readMore(buf, conn, c)) {
iqueue.add(conn);
}
if (buf.hasRemaining()) {
conn.inQueue.put(buf);
queue(conn);
} else {
pushBuffer(buf);
}
} catch (IOException e) {
pushBuffer(buf);
throw e;
}
}
} catch (CancelledKeyException e) {
// an other thread may cancel the key
} catch (ClosedByInterruptException e) {
// do the same stuff as when InterruptedException is thrown
return;
} catch (IOException ex) {
if (key != null) {
key.cancel();
}
handleIOException(key, conn, ex);
} catch (InterruptedException e) {
// FIXME controlled shutdown (e.g. take care of buffermanagement)
return;
}
}
} catch (RuntimeException e) {
// should hopefully never occur
handleFatal(null, e);
} finally {
if (decoders != null) {
for (WebSocketWorker w : decoders) {
w.interrupt();
}
}
if (server != null) {
try {
server.close();
} catch (IOException e) {
onError(null, e);
}
}
}
}
Aggregations