Package java.nio.channels

Examples of java.nio.channels.Selector


        return accept_nonblock(getRuntime().getCurrentContext());
    }
    @JRubyMethod(name = "accept_nonblock")
    public IRubyObject accept_nonblock(ThreadContext context) {
        RubyTCPSocket socket = new RubyTCPSocket(context.getRuntime(), context.getRuntime().fastGetClass("TCPSocket"));
        Selector selector = null;
        try {
            ssc.configureBlocking(false);
            selector = Selector.open();
            SelectionKey key = ssc.register(selector, SelectionKey.OP_ACCEPT);
           
            int selected = selector.selectNow();
            if (selected == 0) {
                // no connection immediately accepted, let them try again
                throw context.getRuntime().newErrnoEAGAINError("Resource temporarily unavailable");
            } else {
                try {
                    // otherwise one key has been selected (ours) so we get the channel and hand it off
                    socket.initSocket(context.getRuntime(), new ChannelDescriptor(ssc.accept(), RubyIO.getNewFileno(), new ModeFlags(ModeFlags.RDWR), new FileDescriptor()));
                } catch (InvalidValueException ex) {
                    throw context.getRuntime().newErrnoEINVALError();
                }
                return socket;
            }
        } catch(IOException e) {
            throw sockerr(context.getRuntime(), "problem when accepting");
        } finally {
            try {
                if (selector != null) selector.close();
            } catch (IOException ioe) {
            }
        }
    }


            RubyIO io = (RubyIO)recv.getInstanceVariables().getInstanceVariable("@io");

            int timeout = RubyNumeric.fix2int(recv.getInstanceVariables().getInstanceVariable("@read_timeout")) * 1000;
            NativeImpl nim = (NativeImpl)recv.dataGetStruct();

            Selector selector = null;
            try {
                selector = Selector.open();
                nim.channel.configureBlocking(false);
                SelectionKey key = nim.channel.register(selector, SelectionKey.OP_READ);
                int n = selector.select(timeout);

                if(n > 0) {
                    IRubyObject readItems = io.read(new IRubyObject[]{recv.getRuntime().newFixnum(1024*16)});
                    return buf.concat(readItems);
                } else {
                    RubyClass exc = (RubyClass)(recv.getRuntime().getModule("Timeout").getConstant("Error"));
                    throw new RaiseException(RubyException.newException(recv.getRuntime(), exc, "execution expired"),false);
                }
            } catch(IOException exception) {
                throw recv.getRuntime().newIOErrorFromException(exception);
            } finally {
                if (selector != null) {
                    try {
                        selector.close();
                    } catch (IOException ioe) {
                    }
                }
            }
        }

            return true;
        }
    }
   
    public void interrupt() {
        Selector selector = currentSelector;
        if (selector != null) {
            selector.wakeup();
        }
        BlockingIO.Condition iowait = blockingIO;
        if (iowait != null) {
            iowait.cancel();
        }

        Channel channel = descriptor.getChannel();
        if (channel == null || !(channel instanceof SelectableChannel)) {
            return false;
        }
      
        Selector selector = Selector.open();

        ((SelectableChannel) channel).configureBlocking(false);
        int real_ops = ((SelectableChannel) channel).validOps() & SelectionKey.OP_WRITE;
        SelectionKey key = ((SelectableChannel) channel).keyFor(selector);
      
        if (key == null) {
            ((SelectableChannel) channel).register(selector, real_ops, descriptor);
        } else {
            key.interestOps(key.interestOps()|real_ops);
        }

        while(selector.select() == 0);

        for (Iterator i = selector.selectedKeys().iterator(); i.hasNext(); ) {
            SelectionKey skey = (SelectionKey) i.next();
            if ((skey.interestOps() & skey.readyOps() & (SelectionKey.OP_WRITE)) != 0) {
                if(skey.attachment() == descriptor) {
                    return true;
                }

        Channel channel = descriptor.getChannel();
        if (channel == null || !(channel instanceof SelectableChannel)) {
            return false;
        }
      
        Selector selector = Selector.open();

        ((SelectableChannel) channel).configureBlocking(false);
        int real_ops = ((SelectableChannel) channel).validOps() & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT);
        SelectionKey key = ((SelectableChannel) channel).keyFor(selector);
      
        if (key == null) {
            ((SelectableChannel) channel).register(selector, real_ops, descriptor);
        } else {
            key.interestOps(key.interestOps()|real_ops);
        }

        while(selector.select() == 0);

        for (Iterator i = selector.selectedKeys().iterator(); i.hasNext(); ) {
            SelectionKey skey = (SelectionKey) i.next();
            if ((skey.interestOps() & skey.readyOps() & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0) {
                if(skey.attachment() == descriptor) {
                    return true;
                }

    public static IRubyObject select_static(ThreadContext context, Ruby runtime, IRubyObject[] args) {
       try {
           Set pending = new HashSet();
           Set unselectable_reads = new HashSet();
           Set unselectable_writes = new HashSet();
           Selector selector = Selector.open();
           if (!args[0].isNil()) {
               // read
               checkArrayType(runtime, args[0]);
               for (Iterator i = ((RubyArray) args[0]).getList().iterator(); i.hasNext(); ) {
                   IRubyObject obj = (IRubyObject) i.next();
                   RubyIO ioObj = convertToIO(context, obj);
                   if (registerSelect(context, selector, obj, ioObj, SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) {
                       if (ioObj.writeDataBuffered()) {
                           pending.add(obj);
                       }
                   } else {
                       if (( ioObj.openFile.getMode() & OpenFile.READABLE ) != 0) {
                           unselectable_reads.add(obj);
                       }
                   }
               }
           }

           if (args.length > 1 && !args[1].isNil()) {
               // write
               checkArrayType(runtime, args[1]);
               for (Iterator i = ((RubyArray) args[1]).getList().iterator(); i.hasNext(); ) {
                   IRubyObject obj = (IRubyObject) i.next();
                   RubyIO ioObj = convertToIO(context, obj);
                   if (!registerSelect(context, selector, obj, ioObj, SelectionKey.OP_WRITE)) {
                       if (( ioObj.openFile.getMode() & OpenFile.WRITABLE ) != 0) {
                           unselectable_writes.add(obj);
                       }
                   }
               }
           }

           if (args.length > 2 && !args[2].isNil()) {
               checkArrayType(runtime, args[2]);
               // Java's select doesn't do anything about this, so we leave it be.
           }

           final boolean has_timeout = ( args.length > 3 && !args[3].isNil() );
           long timeout = 0;
           if(has_timeout) {
               IRubyObject timeArg = args[3];
               if (timeArg instanceof RubyFloat) {
                   timeout = Math.round(((RubyFloat) timeArg).getDoubleValue() * 1000);
               } else if (timeArg instanceof RubyFixnum) {
                   timeout = Math.round(((RubyFixnum) timeArg).getDoubleValue() * 1000);
               } else { // TODO: MRI also can hadle Bignum here
                   throw runtime.newTypeError("can't convert "
                           + timeArg.getMetaClass().getName() + " into time interval");
               }

               if (timeout < 0) {
                   throw runtime.newArgumentError("negative timeout given");
               }
           }
          
           if (pending.isEmpty() && unselectable_reads.isEmpty() && unselectable_writes.isEmpty()) {
               if (has_timeout) {
                   if (timeout==0) {
                       selector.selectNow();
                   } else {
                       selector.select(timeout);                      
                   }
               } else {
                   selector.select();
               }
           } else {
               selector.selectNow();              
           }
          
           List r = new ArrayList();
           List w = new ArrayList();
           List e = new ArrayList();
           for (Iterator i = selector.selectedKeys().iterator(); i.hasNext(); ) {
               SelectionKey key = (SelectionKey) i.next();
               if ((key.interestOps() & key.readyOps()
                       & (SelectionKey.OP_READ|SelectionKey.OP_ACCEPT|SelectionKey.OP_CONNECT)) != 0) {
                   r.add(key.attachment());
                   pending.remove(key.attachment());
               }
               if ((key.interestOps() & key.readyOps() & (SelectionKey.OP_WRITE)) != 0) {
                   w.add(key.attachment());
               }
           }
           r.addAll(pending);
           r.addAll(unselectable_reads);
           w.addAll(unselectable_writes);
          
           // make all sockets blocking as configured again
           for (Iterator i = selector.keys().iterator(); i.hasNext(); ) {
               SelectionKey key = (SelectionKey) i.next();
               SelectableChannel channel = key.channel();
               synchronized(channel.blockingLock()) {
                   RubyIO originalIO = (RubyIO) TypeConverter.convertToType(
                           (IRubyObject) key.attachment(), runtime.getIO(),
                           MethodIndex.TO_IO, "to_io");
                   boolean blocking = originalIO.getBlocking();
                   key.cancel();
                   channel.configureBlocking(blocking);
               }
           }
           selector.close();
          
           if (r.size() == 0 && w.size() == 0 && e.size() == 0) {
               return runtime.getNil();
           }
          

    protected void registerNewSelector() throws IOException {
        synchronized (selector) {
            Set<SelectionKey> keys = selector.keys();

            // Open a new selector
            Selector newSelector = Selector.open();

            // Loop on all the registered keys, and register them on the new selector
            for (SelectionKey key : keys) {
                SelectableChannel ch = key.channel();
               

        }
    }

    void flush(SocketSessionImpl session) {
        if ( scheduleFlush(session) ) {
            Selector selector = this.selector;
            if (selector != null) {
                selector.wakeup();
            }
        }
    }

        }
    }

    void updateTrafficMask(SocketSessionImpl session) {
        scheduleTrafficControl(session);
        Selector selector = this.selector;
        if (selector != null) {
            selector.wakeup();
        }
    }

    private void scheduleTrafficControl(SocketSessionImpl session) {
        trafficControllingSessions.add(session);
    }

    private void doAddNew() {
        Selector selector = this.selector;
        for (;;) {
            SocketSessionImpl session = newSessions.poll();

            if (session == null)
                break;

TOP

Related Classes of java.nio.channels.Selector

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.