本文整理汇总了Java中java.nio.channels.SelectionKey类的典型用法代码示例。如果您正苦于以下问题:Java SelectionKey类的具体用法?Java SelectionKey怎么用?Java SelectionKey使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SelectionKey类属于java.nio.channels包,在下文中一共展示了SelectionKey类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: process
import java.nio.channels.SelectionKey; //导入依赖的package包/类
private void process() {
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove();
if (!key.isValid()) {
continue;
}
ChannelHandler handler = (ChannelHandler) key.attachment();
if (key.isAcceptable()) {
handler.accept(key);
} else if (key.isConnectable()) {
handler.connect(key);
} else if (key.isReadable()) {
handler.read(key);
} else if (key.isWritable()) {
handler.write(key);
}
}
}
示例2: doRead
import java.nio.channels.SelectionKey; //导入依赖的package包/类
void doRead(SelectionKey key) throws InterruptedException {
int count = 0;
Connection c = (Connection)key.attachment();
if (c == null) {
return;
}
c.setLastContact(Time.now());
try {
count = c.readAndProcess();
} catch (InterruptedException ieo) {
LOG.info(Thread.currentThread().getName() + ": readAndProcess caught InterruptedException", ieo);
throw ieo;
} catch (Exception e) {
// a WrappedRpcServerException is an exception that has been sent
// to the client, so the stacktrace is unnecessary; any other
// exceptions are unexpected internal server errors and thus the
// stacktrace should be logged
LOG.info(Thread.currentThread().getName() + ": readAndProcess from client " +
c.getHostAddress() + " threw exception [" + e + "]",
(e instanceof WrappedRpcServerException) ? null : e);
count = -1; //so that the (count < 0) block is executed
}
if (count < 0) {
closeConnection(c);
c = null;
}
else {
c.setLastContact(Time.now());
}
}
示例3: timeoutExceptionString
import java.nio.channels.SelectionKey; //导入依赖的package包/类
private static String timeoutExceptionString(SelectableChannel channel,
long timeout, int ops) {
String waitingFor;
switch(ops) {
case SelectionKey.OP_READ :
waitingFor = "read"; break;
case SelectionKey.OP_WRITE :
waitingFor = "write"; break;
case SelectionKey.OP_CONNECT :
waitingFor = "connect"; break;
default :
waitingFor = "" + ops;
}
return timeout + " millis timeout while " +
"waiting for channel to be ready for " +
waitingFor + ". ch : " + channel;
}
示例4: sendPacket
import java.nio.channels.SelectionKey; //导入依赖的package包/类
public final void sendPacket(final SendablePacket<T> sp)
{
sp._client = _client;
if (_pendingClose)
return;
synchronized (getSendQueue())
{
_sendQueue.addLast(sp);
}
if (!_sendQueue.isEmpty())
{
try
{
_selectionKey.interestOps(_selectionKey.interestOps() | SelectionKey.OP_WRITE);
}
catch (CancelledKeyException e)
{
// ignore
}
}
}
示例5: processAcceptedConnections
import java.nio.channels.SelectionKey; //导入依赖的package包/类
/**
* Iterate over the queue of accepted connections that have been
* assigned to this thread but not yet placed on the selector.
*/
private void processAcceptedConnections() {
SocketChannel accepted;
while (!stopped && (accepted = acceptedQueue.poll()) != null) {
SelectionKey key = null;
try {
key = accepted.register(selector, SelectionKey.OP_READ);
NIOServerCnxn cnxn = createConnection(accepted, key, this);
key.attach(cnxn);
addCnxn(cnxn);
} catch (IOException e) {
// register, createConnection
cleanupSelectionKey(key);
fastCloseSock(accepted);
}
}
}
示例6: run
import java.nio.channels.SelectionKey; //导入依赖的package包/类
@Override
public void run() {
try {
while (true) {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
if (i.hasNext()) {
SelectionKey key = i.next();
keys.remove(key);
handleEvent(key);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
示例7: enqueue
import java.nio.channels.SelectionKey; //导入依赖的package包/类
/**
* Queue a FastSerializable object for writing. This is 2nd best way to serialize and queue messages.
* The expected message size is used to size the initial allocation for the FastSerializer.
* Because FastSerializer is used to serialize the object there is some over head incurred
* when the FastSerializer has to check if it needs to grow, but the cost is pretty minor compared
* to the cost of actually growing the FastSerializer.
* @param f
*/
@Override
public boolean enqueue(final FastSerializable f, final int expectedSize) {
synchronized (this) {
if (m_isShutdown) {
return false;
}
updateLastPendingWriteTimeAndQueueBackpressure();
m_queuedWrites.offer(new DeferredSerialization() {
@Override
public BBContainer serialize(final DBBPool pool) throws IOException {
final FastSerializer fs = new FastSerializer(pool, expectedSize);
return fs.writeObjectForMessaging(f);
}
@Override
public void cancel() {}
});
m_port.setInterests( SelectionKey.OP_WRITE, 0);
}
return true;
}
示例8: connect
import java.nio.channels.SelectionKey; //导入依赖的package包/类
private void connect(Selector selector) {
AbstractConnection c = null;
while ((c = connectQueue.poll()) != null) {
try {
SocketChannel channel = (SocketChannel) c.getChannel();
// 注册 OP_CONNECT(建立连接) 监听与后端连接是否真正建立 // 监听到之后是图-MySql第3步,(TCP连接建立)
channel.register(selector, SelectionKey.OP_CONNECT, c);
// 主动连接 阻塞或者非阻塞 // 图-MySql第1步,(TCP连接请求)
channel.connect(new InetSocketAddress(c.host, c.port));
} catch (Exception e) {
LOGGER.error("error:",e);
c.close(e.toString());
}
}
}
示例9: connectMaster
import java.nio.channels.SelectionKey; //导入依赖的package包/类
private boolean connectMaster() throws ClosedChannelException {
if (null == socketChannel) {
String addr = this.masterAddress.get();
if (addr != null) {
SocketAddress socketAddress = RemotingUtil.string2SocketAddress(addr);
if (socketAddress != null) {
this.socketChannel = RemotingUtil.connect(socketAddress);
if (this.socketChannel != null) {
this.socketChannel.register(this.selector, SelectionKey.OP_READ);
}
}
}
// 每次连接时,要重新拿到最大的Offset
this.currentReportedOffset = HAService.this.defaultMessageStore.getMaxPhyOffset();
this.lastWriteTimestamp = System.currentTimeMillis();
}
return this.socketChannel != null;
}
示例10: onReadable
import java.nio.channels.SelectionKey; //导入依赖的package包/类
public void onReadable(SelectionKey key){
try {
ByteBuffer buffer=GL_BUFFER;
buffer.clear();
int bytesRead=m_InnerChannel.read(buffer);
if(bytesRead>0){
buffer.flip();
afterReceived(buffer);//先让子类处理,例如解密数据。
if(isTunnelEstablished()&&buffer.hasRemaining()){//将读到的数据,转发给兄弟。
m_BrotherTunnel.beforeSend(buffer);//发送之前,先让子类处理,例如做加密等。
if(!m_BrotherTunnel.write(buffer,true)){
key.cancel();//兄弟吃不消,就取消读取事件。
if(ProxyConfig.IS_DEBUG)
System.out.printf("%s can not read more.\n", m_ServerEP);
}
}
}else if(bytesRead<0) {
this.dispose();//连接已关闭,释放资源。
}
} catch (Exception e) {
e.printStackTrace();
this.dispose();
}
}
示例11: testInvokeCallbacks
import java.nio.channels.SelectionKey; //导入依赖的package包/类
public void testInvokeCallbacks() throws InterruptedException{
MockSelector selector = new MockSelector();
VoltNetwork vn = new VoltNetwork(selector); // network with fake selector
MockVoltPort vp = new MockVoltPort(vn, new MockInputHandler()); // implement abstract run()
MockSelectionKey selectionKey = new MockSelectionKey(); // fake selection key
// glue the key, the selector and the port together.
selectionKey.interestOps(SelectionKey.OP_WRITE);
selector.setFakeKey(selectionKey);
vp.m_selectionKey = selectionKey;
selectionKey.attach(vp);
selectionKey.readyOps(SelectionKey.OP_WRITE);
// invoke call backs and see that the volt port has the expected
// selected operations.
vn.invokeCallbacks();
assertEquals(SelectionKey.OP_WRITE, vp.readyOps());
// and another time through, should have the new interests selected
vp.setInterests(SelectionKey.OP_ACCEPT, 0);
selectionKey.readyOps(SelectionKey.OP_ACCEPT);
vn.installInterests();
vn.invokeCallbacks();
vn.shutdown();
assertEquals(SelectionKey.OP_ACCEPT, vp.readyOps());
}
示例12: connect
import java.nio.channels.SelectionKey; //导入依赖的package包/类
/**
* Finishes the connection process for the given connection
*
* @param p_key
* the selection key
*/
public void connect(final SelectionKey p_key) throws NetworkException {
if (getPipeOut().getChannel().isConnectionPending()) {
try {
if (getPipeOut().getChannel().finishConnect()) {
connected(p_key);
} else {
// #if LOGGER >= ERROR
LOGGER.error("Connection could not be finished: %s", this);
// #endif /* LOGGER >= ERROR */
}
} catch (final IOException ignore) {
abortConnectionCreation();
}
} else {
// #if LOGGER >= WARN
LOGGER.warn("Connection is not pending, connect aborted: %s", this);
// #endif /* LOGGER >= WARN */
}
}
示例13: main
import java.nio.channels.SelectionKey; //导入依赖的package包/类
public static void main(String[] argv) throws Exception {
try (ByteServer server = new ByteServer();
SocketChannel sc = SocketChannel.open(server.address())) {
server.acceptConnection();
try (Selector sel = Selector.open()) {
sc.configureBlocking(false);
sc.register(sel, SelectionKey.OP_WRITE);
sel.select();
sel.selectedKeys().clear();
if (sel.select() == 0) {
throw new Exception("Select returned zero");
}
}
}
}
示例14: close
import java.nio.channels.SelectionKey; //导入依赖的package包/类
@Override
protected void close(DatagramChannel handle) throws Exception {
SelectionKey key = handle.keyFor(selector);
if (key != null) {
key.cancel();
}
handle.disconnect();
handle.close();
}
示例15: Client
import java.nio.channels.SelectionKey; //导入依赖的package包/类
public Client() throws IOException {
// 同样的,注册闹钟.
this.selector = Selector.open();
// 连接远程server
socketChannel = SocketChannel.open();
// 如果快速的建立了连接,返回true.如果没有建立,则返回false,并在连接后出发Connect事件.
Boolean isConnected = socketChannel.connect(new InetSocketAddress("localhost", 3562));
socketChannel.configureBlocking(false);
SelectionKey key = socketChannel.register(selector, SelectionKey.OP_READ);
if (isConnected) {
this.sendFirstMsg();
} else {
// 如果连接还在尝试中,则注册connect事件的监听. connect成功以后会出发connect事件.
key.interestOps(SelectionKey.OP_CONNECT);
}
}