本文整理汇总了Java中java.nio.channels.SelectionKey.channel方法的典型用法代码示例。如果您正苦于以下问题:Java SelectionKey.channel方法的具体用法?Java SelectionKey.channel怎么用?Java SelectionKey.channel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.nio.channels.SelectionKey
的用法示例。
在下文中一共展示了SelectionKey.channel方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: doAsyncWrite
import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
private void doAsyncWrite(SelectionKey key) throws IOException {
Connection connection = (Connection) key.attachment();
if (connection == null) {
throw new IOException("doAsyncWrite: no connection");
}
if (key.channel() != connection.channel) {
throw new IOException("doAsyncWrite: bad channel");
}
if (processAllResponses(connection)) {
try {
// We wrote everything, so we don't need to be told when the socket is ready for
// write anymore.
key.interestOps(0);
} catch (CancelledKeyException e) {
/* The Listener/reader might have closed the socket.
* We don't explicitly cancel the key, so not sure if this will
* ever fire.
* This warning could be removed.
*/
LOG.warn("Exception while changing ops : " + e);
}
}
}
示例2: handle
import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
private void handle(SelectionKey key) {
SocketChannel channel = (SocketChannel) key.channel();
if (key.isConnectable()) {
try {
if (channel.finishConnect()) {
//connect finish
this.logger.info("[Connecter] finish connect " + channel.getRemoteAddress().toString());
IoWorker worker = this.workers.get(workersIndex);
worker.dispatch(new JobBean(channel, this.chanToParam.get(channel)));
workersIndex = (workersIndex + 1) % workers.size();
}
} catch (IOException e) {
this.logger.info("[Connecter] finish connect error : " + e.toString());
ClientParam clientParam = this.chanToParam.get(channel);
if (clientParam.getOnConnectError() != null) {
clientParam.getOnConnectError().onConnectError(e);
}
this.chanToParam.remove(channel);
try {
channel.close();
} catch (IOException e1) {
// already close
}
}
}
}
示例3: doAccept
import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
private void doAccept(SelectionKey sk){
ServerSocketChannel server=(ServerSocketChannel)sk.channel();
SocketChannel clientChannel;
try {
//获取客户端的channel
clientChannel = server.accept();
clientChannel.configureBlocking(false);
//register the channel for reading
SelectionKey clientKey=clientChannel.register(selector,SelectionKey.OP_READ);
//Allocate an EchoClient instance and attach it to this selection key.
EchoClient echoClient=new EchoClient();
clientKey.attach(echoClient);
InetAddress clientAddress=clientChannel.socket().getInetAddress();
System.out.println("Accepted connetion from "+clientAddress.getHostAddress()+".");
}catch (Exception e){
System.out.println("Failed to accept new client");
e.printStackTrace();
}
}
示例4: doWrite
import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
private void doWrite(SelectionKey sk){
SocketChannel channel=(SocketChannel)sk.channel();
EchoClient echoClient=(EchoClient)sk.attachment();
LinkedList<ByteBuffer> outq=echoClient.getOutputQueue();
ByteBuffer bb=outq.getLast();
try {
int len=channel.write(bb);
if(len==-1){
disconnect(sk);
return;
}
if(bb.remaining()==0){
outq.removeLast();
}
}catch (Exception e){
e.printStackTrace();
System.out.println("fail to write to client");
disconnect(sk);
}
if(outq.size()==0){
sk.interestOps(SelectionKey.OP_READ);
}
}
示例5: buildChannel
import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
public KafkaChannel buildChannel(String id, SelectionKey key, int maxReceiveSize) throws KafkaException {
try {
SocketChannel socketChannel = (SocketChannel) key.channel();
TransportLayer transportLayer = buildTransportLayer(id, key, socketChannel);
Authenticator authenticator;
if (mode == Mode.SERVER)
authenticator = new SaslServerAuthenticator(id, jaasContext, loginManager.subject(),
kerberosShortNamer, socketChannel.socket().getLocalAddress().getHostName(), maxReceiveSize,
credentialCache);
else
authenticator = new SaslClientAuthenticator(id, loginManager.subject(), loginManager.serviceName(),
socketChannel.socket().getInetAddress().getHostName(), clientSaslMechanism, handshakeRequestEnable);
// Both authenticators don't use `PrincipalBuilder`, so we pass `null` for now. Reconsider if this changes.
authenticator.configure(transportLayer, null, this.configs);
return new KafkaChannel(id, transportLayer, authenticator, maxReceiveSize);
} catch (Exception e) {
log.info("Failed to create channel due to ", e);
throw new KafkaException(e);
}
}
示例6: connect
import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
public void connect(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
// 首先判断是否连接已经建立,如果没有,则调用finishConnect()完成连接
if (channel.isConnectionPending()) {
channel.finishConnect();
}
channel.configureBlocking(false);
//建立连接后,向Channel写入数据,并同时注册读事件为感兴趣的事件
channel.write(ByteBuffer.wrap(new String("hello server!\r\n").getBytes()));
channel.register(this.selector, SelectionKey.OP_READ);
}
示例7: read
import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
private void read(SelectionKey key) throws Exception {
// 服务器可读消息,得到事件发生的socket通道
SocketChannel channel = (SocketChannel) key.channel();
// 穿件读取的缓冲区
ByteBuffer buffer = ByteBuffer.allocate(10);
channel.read(buffer);
byte[] data = buffer.array();
String msg = new String(data).trim();
System.out.println("server receive from client: " + msg);
ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
channel.write(outBuffer);
}
示例8: read
import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
private void read(SelectionKey k) {
try {
SocketChannel channel = (SocketChannel) k.channel();
ByteBuffer data = ByteBuffer.allocate(100000);
data.clear();
channel.read(data);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data.array()));
Object obj = ois.readObject();
if (!isReady() && !(obj instanceof PublicKey))
return;
if (obj instanceof PublicKey) {
setPublicKey((PublicKey) obj);
return;
}
if (!(obj instanceof MeviusPacket))
return;
MeviusPacket packet = (MeviusPacket) obj;
handler.callEvent(MeviusHandler.getPacketEventInstance(packet,
handler.getClientHandler().getClient(channel.socket().getInetAddress().getHostAddress()),
PacketEventType.RECEIVE));
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
if (e.getClass().equals(StreamCorruptedException.class))
try {
disconnect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
示例9: doTransport
import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
@Override
void doTransport(int waitTimeOut, List<Packet> pendingQueue, ClientCnxn cnxn)
throws IOException, InterruptedException {
selector.select(waitTimeOut);
Set<SelectionKey> selected;
synchronized (this) {
selected = selector.selectedKeys();
}
// Everything below and until we get back to the select is
// non blocking, so time is effectively a constant. That is
// Why we just have to do this once, here
updateNow();
for (SelectionKey k : selected) {
SocketChannel sc = ((SocketChannel) k.channel());
if ((k.readyOps() & SelectionKey.OP_CONNECT) != 0) {
if (sc.finishConnect()) {
updateLastSendAndHeard();
updateSocketAddresses();
sendThread.primeConnection();
}
} else if ((k.readyOps() & (SelectionKey.OP_READ | SelectionKey.OP_WRITE)) != 0) {
doIO(pendingQueue, cnxn);
}
}
if (sendThread.getZkState().isConnected()) {
if (findSendablePacket(outgoingQueue,
sendThread.tunnelAuthInProgress()) != null) {
enableWrite();
}
}
selected.clear();
}
示例10: send
import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
/**
* 把sendBuffer中的数据发送给Server,然后删除已发送的数据
* @param key
* @throws IOException
*/
private void send(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
synchronized (sendBuffer){
sendBuffer.flip();//把极限设置为位置,把位置设置为0
socketChannel.write(sendBuffer);//发送数据
sendBuffer.compact();//删除已经发送的数据
}
}
示例11: handleTimeout
import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
private void handleTimeout(){
Selector tmpsel = selector;
Set keys = (stoped == false && tmpsel!=null)?tmpsel.keys():null;
if ( keys == null ) {
return;
}
Iterator it = keys.iterator();
long now = System.currentTimeMillis();
//cancel timeout and no interestOps keys,close socket and channel
while(it.hasNext()){
SelectionKey key = (SelectionKey) it.next();
if(key.channel() instanceof ServerSocketChannel){
continue;
}
if(key.isValid() == false){
continue;
}
try{
MessengerTask task = (MessengerTask)key.attachment();
if(task == null){
cancelKey(key);
continue;
}
if(task.isWritePending() == false && now - task.getLastActive() > sockTimout){
cancelKey(key);
}
}catch(CancelledKeyException e){
cancelKey(key);
}
}
}
示例12: doTransport
import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
@Override
void doTransport(int waitTimeOut, List<Packet> pendingQueue, LinkedList<Packet> outgoingQueue,
ClientCnxn cnxn)
throws IOException, InterruptedException {
selector.select(waitTimeOut);
Set<SelectionKey> selected;
synchronized (this) {
selected = selector.selectedKeys();
}
// Everything below and until we get back to the select is
// non blocking, so time is effectively a constant. That is
// Why we just have to do this once, here
updateNow();
for (SelectionKey k : selected) {
SocketChannel sc = ((SocketChannel) k.channel());
if ((k.readyOps() & SelectionKey.OP_CONNECT) != 0) {
if (sc.finishConnect()) {
updateLastSendAndHeard();
sendThread.primeConnection();
}
} else if ((k.readyOps() & (SelectionKey.OP_READ | SelectionKey.OP_WRITE)) != 0) {
doIO(pendingQueue, outgoingQueue, cnxn);
}
}
if (sendThread.getZkState().isConnected()) {
synchronized(outgoingQueue) {
if (findSendablePacket(outgoingQueue,
cnxn.sendThread.clientTunneledAuthenticationInProgress()) != null) {
enableWrite();
}
}
}
selected.clear();
}
示例13: connect
import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
@Override
public void connect(SelectionKey key) {
logger.info("connect to server");
SocketChannel sc = (SocketChannel) key.channel();
try {
while (!sc.finishConnect()) {
}
key.interestOps(SelectionKey.OP_READ);
} catch (IOException e) {
e.printStackTrace();
}
}
示例14: next
import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
/**
* Get the next SocketChannel in the operator we have built from
* the selected-key et for this selector.
*
* @return The next SocketChannel in the iterator
*/
public ServerSocketChannel next() {
SelectionKey key = iterator.next();
if (key.isValid() && key.isAcceptable()) {
return (ServerSocketChannel) key.channel();
}
return null;
}
示例15: read
import java.nio.channels.SelectionKey; //导入方法依赖的package包/类
private void read(SelectionKey key) throws Exception {
SocketChannel channel = (SocketChannel) key.channel();
// 穿件读取的缓冲区
ByteBuffer buffer = ByteBuffer.allocate(10);
channel.read(buffer);
byte[] data = buffer.array();
String msg = new String(data).trim();
System.out.println("client receive msg from server:" + msg);
ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
channel.write(outBuffer);
}