Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
  * JBoss, Home of Professional Open Source
  * Copyright 2005, JBoss Inc., and individual contributors as indicated
  * by the @authors tag. See the copyright.txt in the distribution for a
  * full listing of individual contributors.
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
 
 /*
  * Created on Jul 23, 2005
  */
 
 package org.jboss.remoting.transport.multiplex;
 
 import  org.jboss.logging.Logger;
 
 import java.util.List;
 import java.util.Map;


VirtualServerSocket is one of the two implementations of a server socket in the Multiplex project. Each VirtualServerSocket belongs to an existing virtual socket group, and each VirtualScoket it creates is added to that virtual socket group. For more details, see the Multiplex documentation on the labs.jboss.org web site.

Most of the methods in VirtualServerSocket override those in its parent class, java.net.ServerSocket. For method descriptions, see the ServerSocket javadoc.

Copyright (c) 2005

Deprecated:
As of release 2.4.0 the multiplex transport will no longer be actively supported.
Author(s):
Ron Sigal
 
 public class VirtualServerSocket extends ServerSocket implements Serializable
 {
    private static final Logger log = Logger.getLogger(VirtualServerSocket.class);
    private List acceptingThreads = Collections.synchronizedList(new LinkedList());
 
    private Map configuration = new HashMap();
    private MultiplexingManager manager;
    private MultiplexingInputStream is;
    private MultiplexingInputStream cis;
    private Protocol protocol;
    private Socket actualSocket;
    private int timeout;
    private boolean bound = false;
    private boolean connected = false;
    private boolean closed = false;
    private Socket dummySocket;
    private static final long serialVersionUID = -5320724929164012313L;
 
 //////////////////////////////////////////////////////////////////////////////////////////////////
 ///        The following constructors duplicate those of the parent class ServerSocket        '///
 //////////////////////////////////////////////////////////////////////////////////////////////////
 

Throws:
java.io.IOException
 
    public VirtualServerSocket() throws IOException
    {
    }


See superclass javadoc.

Parameters:
port
Throws:
IOException
   public VirtualServerSocket(int portthrows IOException
   {
      bind(new InetSocketAddress(port));
      .debug("created VirtualServerSocket: " + toString());
   }


See superclass javadoc.

Parameters:
port
backlog
Throws:
java.io.IOException
   public VirtualServerSocket(int portint backlogthrows IOException
   {
      this(port);
      .warn("backlog parameter is ignored");
      .debug("created VirtualServerSocket: " + toString());
   }

See superclass javadoc.

Parameters:
port
backlog
bindAddr
Throws:
java.io.IOException
   public VirtualServerSocket(int portint backlogInetAddress bindAddrthrows IOException
   {
      bind(new InetSocketAddress(bindAddrport));
      .warn("backlog parameter is ignored");
      .debug("created VirtualServerSocket: " + toString());
   }
//////////////////////////////////////////////////////////////////////////////////////////////////
///           The following constructors are particular to VirtualServerSocket        '///
//////////////////////////////////////////////////////////////////////////////////////////////////
See superclass javadoc.

Parameters:
configuration
   public VirtualServerSocket(VirtualSocket socketMap configurationthrows IOException
   {
      this. = socket.getActualSocket();
      if (configuration != null)
         this..putAll(configuration);
       = socket.getManager();
      bind(new InetSocketAddress(socket.getLocalAddress(), socket.getLocalPort()));
      .debug("created VirtualServerSocket: " + toString());
   }


See superclass javadoc.

Parameters:
timeout
configuration
port
Throws:
IOException
   public VirtualServerSocket(InetSocketAddress remoteAddressInetSocketAddress localAddressint timeoutMap configuration)
   throws IOException
   {
      if (configuration != null)
         this..putAll(configuration);
      connect(remoteAddresslocalAddresstimeout);
      .debug("created VirtualServerSocket: " + toString());
   }
//////////////////////////////////////////////////////////////////////////////////////////////////
///                  The following methods are required of any ServerSocket                   '///
//////////////////////////////////////////////////////////////////////////////////////////////////
   /*
     ok: public void bind(SocketAddress endpoint) throws IOException;
     ok: public void bind(SocketAddress endpoint, int backlog) throws IOException;
     ok: public InetAddress getInetAddress();
     ok: public int getLocalPort();
     ok: public SocketAddress getLocalSocketAddress();
     ok: public Socket accept() throws IOException;
     ok: public void close() throws IOException;
     ok: public ServerSocketChannel getChannel();
     ok: public boolean isBound();
     ok: public boolean isClosed();
     ok: public void setSoTimeout(int timeout) throws SocketException;
     ok: public int getSoTimeout() throws IOException;
     ok: public void setReuseAddress(boolean on) throws SocketException;
     ok: public boolean getReuseAddress() throws SocketException;
     ok: public String toString();
     ok: public void setReceiveBufferSize(int size) throws SocketException;
     ok: public int getReceiveBufferSize() throws SocketException;
   */

See superclass javadoc.
   public synchronized Socket accept() throws IOException
   {
      .debug("entering accept()");
      long start = System.currentTimeMillis();
      int timeout = getSoTimeout();
      int timeLeft = 0;
      if (isClosed())
         throw new SocketException("Socket is closed");
      if (!isBound())
         throw new SocketException("Socket is not bound yet");
      SecurityManager security = System.getSecurityManager();
      if (security != null)
      {
      }
      Thread currentThread = Thread.currentThread();
      .add(currentThread);
      VirtualSocket virtualSocket = null;
      try
      {
         if (timeout > 0)
            if ((timeLeft = timeout - (int) (System.currentTimeMillis() - start)) <= 0)
            {
               .error("timed out");
               throw new SocketTimeoutException("Accept timed out");
            }
         .debug("timeLeft: " + timeLeft);
         SocketId clientPort = .acceptConnect(timeLeft);
         .debug("clientPort:  " + clientPort.getPort());
         virtualSocket = new VirtualSocket(clientPort);
         .incrementReferences();
         int localPort = virtualSocket.getLocalVirtualPort();
         .answerConnect((MultiplexingOutputStreamvirtualSocket.getOutputStream(), localPort);
         return virtualSocket;
      }
      catch (IOException e)
      {
         if (e instanceof InterruptedIOException
             || "Socket closed".equals(e.getMessage())
             || "An existing connection was forcibly closed by the remote host".equals(e.getMessage()))
           .debug(e);
         else
            .error(e);
         if (virtualSocket != null)
            virtualSocket.close();
         if (isClosed())
            throw new SocketException("Socket closed");
         if (e instanceof SocketTimeoutException)
            throw new SocketTimeoutException("Accept timed out");
         throw e;
      }
      finally
      {
         .remove(currentThread);
         if (isClosed())
         {
            if (virtualSocket != null)
               virtualSocket.close();
            throw new SocketException("Socket closed");
         }
      }
   }


See superclass javadoc.
   public void bind(SocketAddress socketAddressthrows IOException
   {
      bind(socketAddress, 1);
   }


See superclass javadoc.
   public void bind(SocketAddress socketAddressint backlogthrows IOException
   {
      if (backlog != 1)
      {
         .warn("backlog != 1: ignored");
      }
      if (isClosed())
         throw new SocketException("Socket is closed");
      if (isBound())
         throw new SocketException("Already bound");
      if (socketAddress == null)
         socketAddress = new InetSocketAddress(0);
      if (!(socketAddress instanceof InetSocketAddress))
         throw new IllegalArgumentException("Unsupported address type");
      InetSocketAddress inetSocketAddress = (InetSocketAddresssocketAddress;
      if (inetSocketAddress.isUnresolved())
         throw new SocketException("Unresolved address");
      SecurityManager security = System.getSecurityManager();
      if (security != null)
         security.checkListen(inetSocketAddress.getPort());
      if ( == null)
      {
          = MultiplexingManager.getaManagerByLocalAddress(inetSocketAddress);
          = .getSocket();
      }
      try
      {
          = true;
          = .registerServerSocket(this);
         .setTimeout();
         .setTimeout();
         if (.isConnected())
         {
             = .getProtocol();
            // remote MultiplexingManager might be shutting down and refuse to register ServerSocket
             = true;
         }
      }
      catch (IOException e)
      {
          = false;
         if (.isServerSocketRegistered())
            .unRegisterServerSocket(this);
         throw e;
      }
      .debug(toString());
   }


See superclass javadoc.
   public void close() throws IOException
   {
      if (isClosed())
         return;
       = true;
      // Try once to interrupt accepting threads.
      if (!.isEmpty())
      {
         // We get a copy of acceptingThreads to avoid a ConcurrentModificationException when a thread
         // removes itself from acceptingThreads.
         LinkedList threads = new LinkedList();
         Iterator it = threads.iterator();
         while (it.hasNext())
         {
            Thread t = (Threadit.next();
            t.interrupt();
            .debug("interrupting accepting thread: " + t.getName());
         }
         if (!.isEmpty())
         {
            MultiplexingManager.addToPendingActions(new PendingClose(this));
         }
      }
      // We want the unregister request to go out to the remote MultiplexingManager first.
      // This way, if the local unregister request causes the local MultiplexingManager to
      // shut down, the remote MultiplexingManager will get the unregisterRemoteServerSocket
      // request before it gets the shutdown manager request.
      if ( != null)
      if ( != null)
         .unRegisterServerSocket(this);
   }


See superclass javadoc.
   {
      if ( == null)
         return null;
      return .getInetAddress();
   }


See superclass javadoc.
   public int getLocalPort()
   {
      if ( == null)
         return -1;
      return .getLocalPort();
   }


See superclass javadoc.
   {
      return null;
   }


See superclass javadoc.
   {
      if ( == null)
         return null;
      return .getLocalSocketAddress();
   }


See superclass javadoc.
   public int getReceiveBufferSize() throws SocketException
   {
      if ( == null)
      {
         if ( == null)
             = new Socket();
         return .getReceiveBufferSize();
      }
      return .getReceiveBufferSize();
   }


See superclass javadoc.
   public boolean getReuseAddress() throws SocketException
   {
      if ( == null)
         return true;
      else
         return .getReuseAddress();
   }


See superclass javadoc.
   public int getSoTimeout() throws SocketException
   {
      if (isClosed())
         throw new SocketException("Socket is closed");
      return ;
   }


See superclass javadoc.
   public boolean isBound()
   {
      return ;
   }


See superclass javadoc.
   public boolean isClosed()
   {
      return ;
   }


See superclass javadoc.
   public void setReceiveBufferSize (int sizethrows SocketException
   {
      if ( != null)
         .setReceiveBufferSize(size);
   }


See superclass javadoc.
   public void setReuseAddress(boolean onthrows SocketException
   {
      if ( != null)
         .setReuseAddress(on);
   }


See superclass javadoc.
   public void setSoTimeout(int timeoutthrows SocketException
   {
      if (isClosed())
         throw new SocketException("Socket is closed");
      if (timeout < 0)
         throw new IllegalArgumentException("timeout can't be negative");
      this. = timeout;
      if ( != null)
         .setTimeout(timeout);
      if ( != null)
         .setTimeout(timeout);
   }


See superclass javadoc.
   public String toString()
   {
      StringBuffer answer = new StringBuffer().append("VirtualServerSocket[");
      if ( == null)
         answer.append("unbound");
      else
         answer.append(.toString());
      return answer.append("]").toString();
   }
   //////////////////////////////////////////////////////////////////////////////////////////////////
   ///             The following methods are specific to VirtualServerSocket           '///
   //////////////////////////////////////////////////////////////////////////////////////////////////

   
See superclass javadoc.
   public void connect(SocketAddress remoteAddressthrows IOException
   {
      connect(remoteAddressnull);
   }


Connects this socket to the server. See superclass javadoc.
   public void connect(SocketAddress remoteAddressSocketAddress localAddressthrows IOException
   {
      connect(remoteAddresslocalAddress);
   }


See superclass javadoc.
   public void connect(SocketAddress remoteAddressSocketAddress localAddressint timeoutthrows IOException
   {
      long start = System.currentTimeMillis();
      int timeLeft = 0;
      if (remoteAddress == null)
         throw new IllegalArgumentException("connect: The address can't be null");
      if (timeout < 0)
         throw new IllegalArgumentException("connect: timeout can't be negative");
      if (isClosed())
         throw new SocketException("Socket is closed");
      if (!(remoteAddress instanceof InetSocketAddress))
         throw new IllegalArgumentException("Unsupported address type");
      InetSocketAddress remoteInetSocketAddress = (InetSocketAddressremoteAddress;
      SecurityManager security = System.getSecurityManager();
      if (security != null)
      {
         if (remoteInetSocketAddress.isUnresolved())
            security.checkConnect(remoteInetSocketAddress.getHostName(), remoteInetSocketAddress.getPort());
         else
            security.checkConnect(remoteInetSocketAddress.getAddress().getHostAddress(), remoteInetSocketAddress.getPort());
      }
      // Binding entails getting a MultiplexingManager, which might already be connected,
      // thereby putting the ServerSocket in a connected state.  Therefore, we allow connect() to be
      // called on a connected ServerSocket, as long as the host to which it is to be connected
      // is the same as the host to which it is already connected.
      if (isConnected())
         if (getRemoteAddress().equals(remoteInetSocketAddress.getAddress()))
            return;
         else
            throw new SocketException("already connected");
      if ( == null)
      {
         if (timeout > 0)
            if ((timeLeft = timeout - (int) (System.currentTimeMillis() - start)) <= 0)
               throw new SocketTimeoutException("connect timed out");
         if (localAddress == null)
             = MultiplexingManager.getaManagerByRemoteAddress(remoteInetSocketAddress,
                                                                     timeLeft);
         else
         {
            InetSocketAddress localInetSocketAddress = (InetSocketAddresslocalAddress;
             = MultiplexingManager.getaManagerByAddressPair(remoteInetSocketAddress,
                                                                   localInetSocketAddress,
                                                                   timeLeft,
                                                                   );
         }
      }
       = .getSocket();
      try
      {
         if (!isBound())
         {
            .debug("calling registerServerSocket()");
             = .registerServerSocket(this);
             = .getAnInputStream(.null);
            .setTimeout(this.);
            .setTimeout(this.);
             = true;
         }
         // If the manager is not connected, we need to connect to the remote MasterServerSocket, which
         // will create a real socket and a MultiplexingManager to wrap it.
         if (!.isConnected())
         {
            if (timeout > 0)
               if ((timeLeft = timeout - (int) (System.currentTimeMillis() - start)) <= 0)
                  throw new SocketTimeoutException("connect timed out");
            .connect(remoteInetSocketAddresstimeLeft);
             = .getProtocol();
            if (timeout > 0)
               if ((timeLeft = timeout - (int) (System.currentTimeMillis() - start)) <= 0)
                  throw new SocketTimeoutException("connect timed out");
            .setTimeout(timeout);
            .connect(.timeLeft);
            // Remote MultiplexingManager might be shutting down and refuse to register ServerSocket.
            // If so, registerRemoteServerSocket() will throw an IOException
            if (timeout > 0)
               if ((timeLeft = timeout - (int) (System.currentTimeMillis() - start)) <= 0)
                  throw new SocketTimeoutException("connect timed out");
         }
         else
             = .getProtocol();
         if (timeout > 0)
            if ((timeLeft = timeout - (int) (System.currentTimeMillis() - start)) <= 0)
               throw new SocketTimeoutException("connect timed out");
         .registerRemoteServerSocket(timeLeft);
      }
      catch (IOException e)
      {
         .error("i/o exception in VirtualServerSocket.connect()"e);
         if (.isServerSocketRegistered())
            .unRegisterServerSocket(this);
         if (e instanceof SocketTimeoutException)
            throw new SocketTimeoutException("connect timed out");
         throw e;
      }
      finally
      {
         if ( != null)
            .setTimeout(this.);
      }
       = true;
      .debug(toString());
   }


Returns:
   {
      return ;
   }



See superclass javadoc.
   public boolean isConnected()
   {
      return ;
   }


See superclass javadoc.
   {
      if ( == null)
         return null;
      return .getInetAddress();
   }


See superclass javadoc.
   public int getRemotePort()
   {
      if ( == null)
         return 0;
      return .getPort();
   }


See superclass javadoc.
   public void setConfiguration(Map configuration)
   {
      this..putAll(configuration);
   }


   protected void doClose()
   {
      // We get a copy of acceptingThreads to avoid a ConcurrentModificationException when a thread
      // removes itself from acceptingThreads.
      LinkedList threads = new LinkedList();
      Iterator it = threads.iterator();
      while (it.hasNext())
      {
         Thread t = (Threadit.next();
         t.interrupt();
         .debug("interrupting accepting thread: " + t.getName());
         // Make sure the accepting thread caught the interrupt.
         while (.contains(t))
         {
            try
            {
               .debug("waiting for accepting thread to catch interrupt: " + t.getName());
               Thread.sleep(500);
               t.interrupt();
               .debug("interrupting accepting thread: " + t.getName());
            }
            catch (InterruptedException ignored) {}
         }
      }
   }
   protected class PendingClose extends PendingAction
   {
      public PendingClose(Object o)
      {
         super(o);
      }
      public void doAction()
      {
         ((VirtualServerSocket).doClose();
      }
   }
New to GrepCode? Check out our FAQ X