Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
BEGIN LICENSE BLOCK ***** Version: EPL 1.0/GPL 2.0/LGPL 2.1 The contents of this file are subject to the Eclipse Public License Version 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.eclipse.org/legal/epl-v10.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Copyright (C) 2007 Ola Bini <ola@ologix.com> Alternatively, the contents of this file may be used under the terms of either of the GNU General Public License Version 2 or later (the "GPL"), or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms of the EPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the EPL, the GPL or the LGPL. END LICENSE BLOCK ***
 
 package org.jruby.ext.socket;
 
 
 import org.jruby.Ruby;
 

Author(s):
Ola Bini
 
 @JRubyClass(name="TCPServer", parent="TCPSocket")
 public class RubyTCPServer extends RubyTCPSocket {
     static void createTCPServer(Ruby runtime) {
         RubyClass rb_cTCPServer = runtime.defineClass(
                 "TCPServer"runtime.getClass("TCPSocket"), );
 
         rb_cTCPServer.defineAnnotatedMethods(RubyTCPServer.class);
 
         runtime.getObject().setConstant("TCPserver",rb_cTCPServer);
     }
 
     private static ObjectAllocator TCPSERVER_ALLOCATOR = new ObjectAllocator() {
         public IRubyObject allocate(Ruby runtimeRubyClass klass) {
             return new RubyTCPServer(runtimeklass);
         }
     };
 
     public RubyTCPServer(Ruby runtimeRubyClass type) {
         super(runtimetype);
     }
 
     @JRubyMethod(name = "initialize", required = 1, optional = 1, visibility = .)
     public IRubyObject initialize(ThreadContext contextIRubyObject[] args) {
         Ruby runtime = context.runtime;
         IRubyObject _host = args[0];
         IRubyObject _port = args.length > 1 ? args[1] : context.nil;
 
         String host;
         if(_host.isNil()|| ((_host instanceof RubyString) && ((RubyString_host).isEmpty())) {
             host = "0.0.0.0";
         } else if (_host instanceof RubyFixnum) {
             // numeric host, use it for port
             _port = _host;
             host = "0.0.0.0";
         } else {
             host = _host.convertToString().toString();
        }
        int port = SocketUtils.getPortFrom(context_port);
        try {
            InetAddress addr = InetAddress.getByName(host);
            ServerSocketChannel ssc = ServerSocketChannel.open();
            InetSocketAddress socket_address = new InetSocketAddress(addrport);
            ssc.socket().bind(socket_address);
            initSocket(runtimenew ChannelDescriptor(sscnewModeFlags(runtime.)));
        } catch(UnknownHostException e) {
            throw SocketUtils.sockerr(runtime"initialize: name or service not known");
        } catch(BindException e) {
            throw runtime.newErrnoEADDRFromBindException(e);
        } catch(SocketException e) {
            String msg = e.getMessage();
            if(msg.indexOf("Permission denied") != -1) {
                throw runtime.newErrnoEACCESError("bind(2)");
            } else {
                throw SocketUtils.sockerr(runtime"initialize: name or service not known");
            }
        } catch(IOException e) {
            throw SocketUtils.sockerr(runtime"initialize: name or service not known");
        } catch (IllegalArgumentException iae) {
            throw SocketUtils.sockerr(runtimeiae.getMessage());
        }
        return this;
    }
    @JRubyMethod(name = "accept")
    public IRubyObject accept(ThreadContext context) {
        Ruby runtime = context.runtime;
        RubyTCPSocket socket = new RubyTCPSocket(runtimeruntime.getClass("TCPSocket"));
        try {
            RubyThread thread = context.getThread();
            while (true) {
                boolean ready = thread.select(this.);
                if (!ready) {
                    // we were woken up without being selected...poll for thread events and go back to sleep
                    context.pollThreadEvents();
                } else {
                    SocketChannel connected = getServerSocketChannel().accept();
                    if (connected == nullcontinue;
                    connected.finishConnect();
                    // Force the client socket to be blocking
                    synchronized (connected.blockingLock()) {
                        connected.configureBlocking(false);
                        connected.configureBlocking(true);
                    }
                    // otherwise one key has been selected (ours) so we get the channel and hand it off
                    socket.initSocket(runtimenew ChannelDescriptor(connectednewModeFlags(runtime.)));
                    return socket;
                }
            }
        } catch(IOException e) {
            throw SocketUtils.sockerr(runtime"problem when accepting");
        }
    }
    @JRubyMethod(name = "accept_nonblock")
    public IRubyObject accept_nonblock(ThreadContext context) {
        Ruby runtime = context.runtime;
        RubyTCPSocket socket = new RubyTCPSocket(runtimeruntime.getClass("TCPSocket"));
        Selector selector = null;
        synchronized (ssc.blockingLock()) {
            boolean oldBlocking = ssc.isBlocking();
            try {
                ssc.configureBlocking(false);
                selector = SelectorFactory.openWithRetryFrom(runtime, SelectorProvider.provider());
                boolean ready = context.getThread().select(this., 0);
                if (!ready) {
                    // no connection immediately accepted, let them try again
                    throw runtime.newErrnoEAGAINError("Resource temporarily unavailable");
                } else {
                    // otherwise one key has been selected (ours) so we get the channel and hand it off
                    socket.initSocket(context.runtimenew ChannelDescriptor(ssc.accept(), newModeFlags(runtime.)));
                    return socket;
                }
            } catch(IOException e) {
                throw SocketUtils.sockerr(context.runtime"problem when accepting");
            } finally {
                try {
                    if (selector != nullselector.close();
                } catch (Exception e) {
                }
                try {ssc.configureBlocking(oldBlocking);} catch (IOException ioe) {}
            }
        }
    }
    @JRubyMethod(name = "listen", required = 1)
    public IRubyObject listen(ThreadContext contextIRubyObject backlog) {
        return RubyFixnum.zero(context.runtime);
    }
    @JRubyMethod(name = "peeraddr", rest = true)
    public IRubyObject peeraddr(ThreadContext contextIRubyObject[] args) {
        throw context.runtime.newNotImplementedError("not supported");
    }
    @JRubyMethod(name = "getpeername", rest = true)
    public IRubyObject getpeername(ThreadContext contextIRubyObject[] args) {
        throw context.runtime.newNotImplementedError("not supported");
    }
    @JRubyMethod(rest = true, meta = true)
    public static IRubyObject open(ThreadContext contextIRubyObject recvIRubyObject[] argsBlock block) {
        IRubyObject tcpServer = recv.callMethod(context"new"args);
        if (!block.isGiven()) return tcpServer;
        try {
            return block.yield(contexttcpServer);
        } finally {
            tcpServer.callMethod(context"close");
        }
    }
        return (ServerSocketChannel)getChannel();
    }
    @Override
    public IRubyObject shutdown(ThreadContext contextIRubyObject[] args) {
        // act like a platform that does not support shutdown for server sockets
        throw context.runtime.newErrnoENOTCONNError();
    }
    @Override
    public IRubyObject gets(ThreadContext context) {
        throw context.runtime.newErrnoENOTCONNError();
    }
    @Override
    public IRubyObject gets(ThreadContext contextIRubyObject sep) {
        throw context.runtime.newErrnoENOTCONNError();
    }
    @Override
    public IRubyObject gets19(ThreadContext context) {
        throw context.runtime.newErrnoENOTCONNError();
    }
    @Override
    public IRubyObject gets19(ThreadContext contextIRubyObject sep) {
        throw context.runtime.newErrnoENOTCONNError();
    }
    @Override
    public IRubyObject gets19(ThreadContext contextIRubyObject sepIRubyObject limit) {
        throw context.runtime.newErrnoENOTCONNError();
    }
    @Deprecated
    public IRubyObject accept() {
        return accept(getRuntime().getCurrentContext());
    }
    @Deprecated
    public IRubyObject listen(IRubyObject backlog) {
        return listen(getRuntime().getCurrentContext(), backlog);
    }
    @Deprecated
    public static IRubyObject open(IRubyObject recvIRubyObject[] argsBlock block) {
        return open(recv.getRuntime().getCurrentContext(), recvargsblock);
    }
New to GrepCode? Check out our FAQ X