⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 socketcontroller.java~2~

📁 移动Agent编程工具Naplet
💻 JAVA~2~
📖 第 1 页 / 共 2 页
字号:
package naplet.nsocket;import java.io.*;import java.net.*;import java.util.*;import java.math.BigInteger;import java.security.*;import javax.security.auth.*;import javax.security.auth.callback.*;import javax.security.auth.login.*;import naplet.NapletID;import naplet.server.*;import naplet.tracing.*;import naplet.*;/** * Controller of this all NapletSocket connection in this machine. * It stores all connection information and provides a channel for * communiction. * * Only one controller for a machine. * <p>Title: </p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2003</p> * <p>Company: </p> * @version 1.0 */public class SocketController    implements Runnable{  /** single instance for  controller*/  private static SocketController instance = null;  /**channel for exchange message*/  public static ControlChannel channel = null;  /** table for NapletSocket*/  private static SocketTable socketTable = new SocketTable();  /**table for server socket, key is socket ID*/  private static SocketTable serverSocketTable = new SocketTable();  /**table for server socket, key is naplet ID*/  private static SocketTable nidServerTable = new SocketTable();  /**running status for current control socket*/  private static boolean bStop;  /**serversocket of this control channel, use to read msg from client*/  private static ServerSocket controlServer;  /** client part of this control channel, create here and keep a copy in   * every napletsocket */  private static Socket controlClient;  /** whether to output some debug info */  static final boolean debug = false;  /** whether check security by changing subject */  private static boolean CHECKRIGHT = false;  /** whether consider security when setup a connection */  static boolean GENKEY = false;  static int ControlPort;  static int UDPPort;  private static ServerProperty property;  public SocketController( ServerProperty property )      throws IOException  {    this.property = property;    ControlPort = property.getControlPort();    UDPPort = property.getControlChannelPort();    channel = new ControlChannel();    // start control channel thread    ( new Thread( channel, "control channel" ) ).start();  }  public SocketController()  {  }  public static SocketController getInstance( ServerProperty property )      throws IOException  {    if ( instance == null )    {      instance = new SocketController( property );    }    return instance;  }  /**   * Called from NapletSocket constructor. Creates a data socket   * and generates   * some control info.   *   * @param nsocket   * @param sid   * @param nid   * @return   * @throws IOException   */  public static Socket registerSocket( NapletSocket nsocket, String sid,                                       NapletID nid )      throws IOException, NoSocketControllerException  {    if ( instance == null )    {      throw new NoSocketControllerException(          "\n\tSocketController is not installed.\n"          + "\n\tPlease provide the SocketControllerPort \n"          + "\tand ControlChannelPort in server configuration file.\n" );    }    if ( nsocket == null )    {      throw new NullPointerException( "nsocket" );    }    if ( sid == null )    {      throw new NullPointerException( "socket id" );    }    if ( nid == null )    {      throw new NullPointerException( "naplet id" );    }    if ( CHECKRIGHT )    {      authorize();    }    String server = locateNaplet( nid );    // socket for data, connect to remote server socket    Socket sock = new Socket( server, ControlPort );    socketTable.put( sid, nsocket );    // should add to nidSocketTable, similiar to server socket,    // for suspendAll(nid);    return sock;  }  /**   * Call from socket handoff in napletsocket(socket)   * Already has data socket under nsocket because of socket handoff.   * No need to create a new one.   * @param nsocket   * @param id   */  public static void registerSocket( NapletSocket nsocket, String sid )      throws IOException, NoSocketControllerException  {    if ( instance == null )    {      throw new NoSocketControllerException(          "\n\tSocketController is not installed.\n"          + "\n\tPlease provide the SocketControllerPort \n"          + "\tand ControlChannelPort in server configuration file.\n" );    }    if ( nsocket == null )    {      throw new NullPointerException( "nsocket" );    }    if ( sid == null )    {      throw new NullPointerException( "sid" );    }    // if suspend/resume in local machine, then may already    // contain the key    if ( !socketTable.containsKey( sid ) )    {      socketTable.put( sid, nsocket );      // should add to nidSocketTable, similiar to server socket    }  }  /**   * No use in this version. just for reference. Called from NapletSocket   * @param nsocket   * @param inetaddress   * @param i   * @param id   * @return   * @throws IOException   */  public static Socket registerSocket( NapletSocket nsocket,                                       InetAddress inetaddress,                                       int i, String id )      throws IOException, NoSocketControllerException  {    if ( instance == null )    {      throw new NoSocketControllerException(          "\n\tSocketController is not installed.\n"          + "\n\tPlease provide the SocketControllerPort \n"          + "\tand ControlChannelPort in server configuration file.\n" );    }    if ( nsocket == null )    {      throw new NullPointerException( "nsocket" );    }    if ( id == null )    {      throw new NullPointerException( "id" );    }    if ( inetaddress == null )    {      throw new NullPointerException( "remoteAddress" );    }    if ( i <= 0 )    {      throw new IllegalArgumentException(          "iRemotePort must be greater than 0" );    }    socketTable.put( id, nsocket );    try    {      Socket socket1 = new Socket( inetaddress, i );      return socket1;    }    catch ( IOException ioexception )    {      socketTable.remove( id );      throw ioexception;    }  }  /**   * Create a server socket and generate some control info.   * @param serversocket   * @param s socket ID   */  public static ServerSocket registerServerSocket(      NapletServerSocket serverNSocket,      NapletID nid, String sid )      throws IOException, NoSocketControllerException  {    if ( instance == null )    {      throw new NoSocketControllerException(          "\n\tSocketController is not installed.\n"          + "\n\tPlease provide the SocketControllerPort \n"          + "\tand ControlChannelPort in server configuration file.\n" );    }    if ( serverNSocket == null )    {      throw new NullPointerException( "serverSocket" );    }    if ( sid == null )    {      throw new NullPointerException( "id" );    }    if ( CHECKRIGHT )    {      authorize();    }    // port management , return a free port upon request.    ServerSocket ss = null;    while ( ss == null )    {      try      {        ss = new ServerSocket( Global.TCPPORT++ );      }      catch ( BindException be )      {        System.out.println( be.getMessage()                            + ",try to get a new one.." );      }    }    serverSocketTable.put( sid, serverNSocket );    log( "---put nid to table:" + nid );    nidServerTable.put( nid.toString(), serverNSocket );    return ss;  }  /**   * create socket client for napletsocket   * @param host   * @param port   * @return   * @throws IOException   */  public static synchronized Socket createSocketChannel(      InetAddress host, int port )      throws IOException, NoSocketControllerException  {    if ( instance == null )    {      throw new NoSocketControllerException(          "\n\tSocketController is not installed.\n"          + "\n\tPlease provide the SocketControllerPort \n"          + "\tand ControlChannelPort in server configuration file.\n" );    }    if ( controlClient == null )    {      controlClient = new Socket( host, port );    }    return controlClient;  }  /**   * Used to create socket for socket controller   * @param host   * @param port   * @return   * @throws IOException   */  public static Socket createSocket( InetAddress host, int port )      throws IOException, NoSocketControllerException  {    if ( instance == null )    {      throw new NoSocketControllerException(          "\n\tSocketController is not installed.\n"          + "\n\tPlease provide the SocketControllerPort \n"          + "\tand ControlChannelPort in server configuration file.\n" );    }    Socket sock = new Socket( host, port );    return sock;  }  /**   * For use in navigator.   * Gets all napletsocket in this machine.   * @return   */  public static Hashtable getSocketTable()  {    return socketTable.getTable();  }  public static void setSocketTable( Hashtable table )  {    if ( table == null )    {      return;    }    for ( Enumeration enum = table.keys();          enum.hasMoreElements(); )    {      String key = ( String ) enum.nextElement();      if ( socketTable.containsKey( key ) )      {        log( "wron update sk tbl aft land:already has the key" );        socketTable.remove( key );      }      socketTable.put( key, table.get( key ) );    }  }  /**   * Get all NapletServerSocket in this host.   * @return   */  public static Hashtable getServerSocketTable()  {    return serverSocketTable.getTable();  }  public static void setServerSocketTable( Hashtable table )  {    if ( table == null )    {      return;    }    for ( Enumeration enum = table.keys();          enum.hasMoreElements(); )    {      String key = ( String ) enum.nextElement();      if ( serverSocketTable.containsKey( key ) )      {        log( "wrong update svr sk tbl aft land:already has the key" );        serverSocketTable.remove( key );      }      serverSocketTable.put( key, table.get( key ) );    }  }  /**   * locate server according to its nid. Locate from directory if available.   * If not, the user must have set it.   * @param nid   * @return   */  private static String locateNaplet( NapletID nid )  {    String host = null;    Locator loc = property.getLocator();    URN svr = null;    try    {      svr = loc.lookup( nid );      host = svr.getHostName();    }    catch ( NapletTracingException ex )    {      NapletMonitor nm = property.getNapletMonitor();      host = nm.locate( nid );    }    return host;  }  /**   * remove napletsocket according to its socketID   * @param id   */  public static void removeSocket( String id )  {    if ( id == null )    {      throw new NullPointerException( "id" );    }    socketTable.remove( id );  }  public static void removeServerSocket( String s )  {    if ( s == null )    {      throw new NullPointerException( "id" );    }    serverSocketTable.remove( s );  }  /**   * This part of function has been moved to NavigotorImpl   *   *  better add a parameter as NapletID   */  public static void suspendAll()  {    for ( Enumeration enum = socketTable.getKeys();          enum.hasMoreElements(); )    {      String s1 = ( String ) enum.nextElement();      NapletSocket nsocket = ( NapletSocket ) socketTable.get( s1 );      //if (nsocket.getNapletID().equals()      // only suspend if is persistent      try      {        //if (nsocket.isPersistent())        nsocket.suspend();      }      catch ( Exception exception )      {        exception.printStackTrace();      }    } // end of for  }  /**   * This part of function has been moved to NavigotorImpl   *   * Resume all connection   */  public static void resumeAll()  {    for ( Enumeration enum1 = socketTable.getKeys();          enum1.hasMoreElements(); )    {      String s1 = ( String ) enum1.nextElement();      NapletSocket nsocket = ( NapletSocket ) socketTable.get( s1 );      try      {        // only need to resume if is persistent        //if(nsocket.isPersistent())        nsocket.resume();      }      catch ( Exception exc )      {        exc.printStackTrace();      }    }  }  /**   * Test if the user has the right to create socket/serversocket. It   * demonstrates the use of subject based security check.   */  static void authorize()  {    SamplePrincipal userPrincipal = new SamplePrincipal( "testUser" );    Subject subject = new Subject();    if ( !subject.getPrincipals().contains( userPrincipal ) )    {      subject.getPrincipals().add( userPrincipal );    }    PrivilegedAction action = new SampleAction();    Subject.doAsPrivileged( subject, action, null );  }  /**   * Message handler for those coming from TCP related to socket handoff.   * Has to be TCP in that case. Others are in UDP.   */  public void run()  {    if ( instance == null )    {      System.out.println( "Please provide the SocketControllerPort " );      System.out.println(          "and ControlChannelPort in the configuration file." );      throw new NullPointerException( "SocketController is not installed" );    }    int i = ControlPort;    // find a free port and start listening. Usually the port    // defined in as ControlPort should be free.    do    {      if ( controlServer != null )      {        break;      }      try      {        controlServer = new ServerSocket( i );        log( "listening on port:" + i );        break;      }      catch ( Exception ex )      {        i++;      }    }    while ( true );    while ( !bStop )    {      try      {        Socket socket1;        try        {          // keep waiting connection, start another          // for waiting if one arrives          socket1 = controlServer.accept();          Thread t = new Thread(              new SocketController(), "control thread" );          t.start();        }        catch ( Exception ex )

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -