Exemplo n.º 1
0
 /** List file names */
 public Enumeration nlst(String s) throws IOException {
   InetAddress inetAddress = InetAddress.getLocalHost();
   byte ab[] = inetAddress.getAddress();
   serverSocket_ = new ServerSocket(0, 1);
   StringBuffer sb = new StringBuffer(32);
   sb.append("PORT ");
   for (int i = 0; i < ab.length; i++) {
     sb.append(String.valueOf(ab[i] & 255));
     sb.append(",");
   }
   sb.append(String.valueOf(serverSocket_.getLocalPort() >>> 8 & 255));
   sb.append(",");
   sb.append(String.valueOf(serverSocket_.getLocalPort() & 255));
   if (issueCommand(sb.toString()) != FTP_SUCCESS) {
     serverSocket_.close();
     throw new IOException(getResponseString());
   } else if (issueCommand("NLST " + ((s == null) ? "" : s)) != FTP_SUCCESS) {
     serverSocket_.close();
     throw new IOException(getResponseString());
   }
   dataSocket_ = serverSocket_.accept();
   serverSocket_.close();
   serverSocket_ = null;
   Vector v = readServerResponse_(dataSocket_.getInputStream());
   dataSocket_.close();
   dataSocket_ = null;
   return (v == null) ? null : v.elements();
 }
Exemplo n.º 2
0
  public void run() throws IOException {
    ServerSocket server = new ServerSocket(this.portNumber);
    this.socket = server.accept();
    this.socket.setTcpNoDelay(true);
    server.close();

    DataInputStream in = new DataInputStream(this.socket.getInputStream());
    final DataOutputStream out = new DataOutputStream(this.socket.getOutputStream());
    while (true) {
      final String className = in.readUTF();
      Thread thread =
          new Thread() {
            public void run() {
              try {
                loadAndRun(className);
                out.writeBoolean(true);
                System.err.println(VerifyTests.class.getName());
                System.out.println(VerifyTests.class.getName());
              } catch (Throwable e) {
                e.printStackTrace();
                try {
                  System.err.println(VerifyTests.class.getName());
                  System.out.println(VerifyTests.class.getName());
                  out.writeBoolean(false);
                } catch (IOException e1) {
                  // ignore
                }
              }
            }
          };
      thread.start();
    }
  }
  private void server() {
    new CountDown(60).start();
    while (true) {
      try {
        Socket socket = serverSock.accept();
        System.out.println("New Client:" + socket);
        if (readyState[6] == 1) {
          System.out.println("正在游戏中,无法加入");
          continue;
        }
        for (i = 0; i <= 5; i++) {
          if (players[i].equals("虚位以待")) break;
        }
        if (i > 5) {
          System.out.println("房间已满,无法加入");
          continue;
        }
        i++;
        ObjectOutputStream remoteOut = new ObjectOutputStream(socket.getOutputStream());
        clients.addElement(remoteOut);

        ObjectInputStream remoteIn = new ObjectInputStream(socket.getInputStream());
        new ServerHelder(remoteIn, remoteOut, socket.getPort(), i).start();
      } catch (IOException e) {
        System.out.println(e.getMessage() + ": Failed to connect to client.");
        try {
          serverSock.close();
        } catch (IOException x) {
          System.out.println(e.getMessage() + ": Failed to close server socket.");
        }
      }
    }
  }
    @Override
    public void run() {

      List<Socket> inProgress = new ArrayList<>();
      ServerSocketFactory factory = ServerSocketFactory.getDefault();

      try {
        ss = factory.createServerSocket(0);
        ss.setSoTimeout(5000);

        socketReadyLatch.countDown();
        while (!interrupted()) {
          inProgress.add(ss.accept()); // eat socket
        }
      } catch (java.net.SocketTimeoutException expected) {
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          ss.close();
        } catch (IOException ignored) {
        }
        for (Socket s : inProgress) {
          try {
            s.close();
          } catch (IOException ignored) {
          }
        }
      }
    }
Exemplo n.º 5
0
  /**
   * Closes the server socket and the connections with all clients. Any exception thrown while
   * closing a client is ignored. If one wishes to catch these exceptions, then clients should be
   * individually closed before calling this method. The method also stops listening if this thread
   * is running. If the server is already closed, this call has no effect.
   *
   * @exception IOException if an I/O error occurs while closing the server socket.
   */
  public final void close() throws IOException {
    if (serverSocket == null) return;
    stopListening();

    try {
      serverSocket.close();
    } finally {
      synchronized (this) {
        // Close the client sockets of the already connected clients
        Thread[] clientThreadList = getClientConnections();
        for (int i = 0; i < clientThreadList.length; i++) {
          try {
            ((ConnectionToClient) clientThreadList[i]).close();
          }
          // Ignore all exceptions when closing clients.
          catch (Exception ex) {
          }
        }
        serverSocket = null;
      }

      try {
        connectionListener.join(); // Wait for the end of listening thread.
      } catch (InterruptedException ex) {
      } catch (NullPointerException ex) {
      } // When thread already dead.

      serverClosed();
    }
  }
Exemplo n.º 6
0
  public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = null;

    try {
      serverSocket = new ServerSocket(10008);
      System.out.println("Enroll: 130050131071");
      System.out.println("Connection Socket Created");
      try {
        while (true) {
          System.out.println("Waiting for Connection");
          new EchoServer2(serverSocket.accept());
        }
      } catch (IOException e) {
        System.err.println("Accept failed.");
        System.exit(1);
      }
    } catch (IOException e) {
      System.err.println("Could not listen on port: 10008.");
      System.exit(1);
    } finally {
      try {
        serverSocket.close();
      } catch (IOException e) {
        System.err.println("Could not close port: 10008.");
        System.exit(1);
      }
    }
  }
Exemplo n.º 7
0
 /** Listens for client requests until stopped. */
 public void run() {
   try {
     while (listener != null) {
       try {
         Socket socket = serverSocket.accept();
         if (!paranoid || checkSocket(socket)) {
           Runner runner = getRunner();
           runner.handle(socket);
           // new Connection (socket);
         } else socket.close();
       } catch (Exception ex) {
         System.err.println("Exception in XML-RPC listener loop (" + ex + ").");
       } catch (Error err) {
         System.err.println("Error in XML-RPC listener loop (" + err + ").");
       }
     }
   } catch (Exception exception) {
     System.err.println("Error accepting XML-RPC connections (" + exception + ").");
   } finally {
     System.err.println("Closing XML-RPC server socket.");
     try {
       serverSocket.close();
       serverSocket = null;
     } catch (IOException ignore) {
     }
   }
 }
 @AfterClass
 public static void tearDownClass() {
   Logger.info(
       HttpClientUtilsTest.class,
       "============= [tearDownClass]global take time milliseconds: "
           + (System.currentTimeMillis() - g_beginTime));
   if (httpServer != null) {
     httpServer.stop(0);
   }
   if (httpServer2 != null) {
     httpServer2.stop(0);
   }
   if (serverSocket != null && !serverSocket.isClosed()) {
     try {
       serverSocket.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   for (Socket s : clientSockets) {
     try {
       if (!s.isClosed()) s.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
Exemplo n.º 9
0
 public void shutdown() {
   try {
     running = false;
     for (WorkerThread t : threads) {
       t.stopThread();
     }
     serverSocket.close();
   } catch (Exception ignore) {
   }
 }
Exemplo n.º 10
0
 public void closeServer() {
   try {
     if (serverSocket_ != null) serverSocket_.close();
     if (dataSocket_ != null) dataSocket_.close();
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     serverSocket_ = null;
     dataSocket_ = null;
     try {
       super.closeServer();
     } catch (Exception e) {
     }
   }
 }
Exemplo n.º 11
0
 public void launch() {
   try {
     ss = new ServerSocket(8888);
     started = true;
     System.out.println("server is start!");
     while (started) {
       s = ss.accept();
       VClient vc = new VClient(s);
       clients.add(vc);
       new Thread(vc).start();
     }
     ss.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 12
0
  public void Shutdown() {
    if (!m_bShutdown) {
      m_bShutdown = true;

      try {
        sf.dataSource.CloseSource();
      } catch (Exception e) {
      }

      try {
        if (m_serverSocket != null) m_serverSocket.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      this.interrupt();
    }
  }
Exemplo n.º 13
0
 public void run() {
   boolean status;
   sf.DEBUG("Listen server running.");
   // open up our server socket
   try {
     m_serverSocket = new ServerSocket(m_nPort);
   } catch (IOException e) {
     sf.VERBOSE("Could not listen on port: " + m_nPort);
     if (sf.cntrlWndw != null) {
       sf.cntrlWndw.ClearListenServer();
     }
     return;
   }
   sf.VERBOSE("Listening for client connections on port " + m_nPort);
   // if (SerialForward.bSourceSim)
   // {
   SetDataSource();
   sf.InitSerialPortIO();
   // }
   // start listening for connections
   try {
     ClientServicer rcv;
     Socket currentSocket;
     while (!m_bShutdown) {
       currentSocket = m_serverSocket.accept();
       ClientServicer newServicer = new ClientServicer(currentSocket, sf, this);
       newServicer.start();
       vctServicers.add(newServicer);
     }
     m_serverSocket.close();
   } catch (IOException e) {
     /*try { this.sleep(500); }
     catch (Exception e2) { }*/
     sf.VERBOSE("Server Socket closed");
   } finally {
     ShutdownAllClientServicers();
     if (sf.serialPortIO != null) sf.serialPortIO.Shutdown();
     sf.VERBOSE("--------------------------");
     if (sf.cntrlWndw != null) {
       sf.cntrlWndw.ClearListenServer();
     }
   }
 }
Exemplo n.º 14
0
 public void run() {
   try {
     while (true) {
       Socket nsk;
       try {
         nsk = sk.accept();
       } catch (IOException e) {
         break;
       }
       new Client(nsk);
     }
   } finally {
     try {
       sk.close();
     } catch (IOException e) {
       throw (new RuntimeException(e));
     }
   }
 }
  public void start() {
    keepGoing = true;
    /* create socket server and wait for connection requests */
    try {
      // the socket used by the server
      ServerSocket serverSocket = new ServerSocket(port);

      // infinite loop to wait for connections
      while (keepGoing) {
        // format message saying we are waiting
        display("Server menunggu koneksi Client pada port " + port + ".");

        Socket socket = serverSocket.accept(); // accept connection
        // if I was asked to stop
        if (!keepGoing) break;
        ClientThread t = new ClientThread(socket); // make a thread of it
        al.add(t); // save it in the ArrayList
        t.start();
      }
      // I was asked to stop
      try {
        serverSocket.close();
        for (int i = 0; i < al.size(); ++i) {
          ClientThread tc = al.get(i);
          try {
            tc.sInput.close();
            tc.sOutput.close();
            tc.socket.close();
          } catch (IOException ioE) {
            // not much I can do
          }
        }
      } catch (Exception e) {
        display("Exception closing the server and clients: " + e);
      }
    }
    // something went bad
    catch (IOException e) {
      String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e + "\n";
      display(msg);
    }
  }
Exemplo n.º 16
0
  public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = null;
    try {
      serverSocket = new ServerSocket(portNumber);
    } catch (IOException e) {
      System.err.println("Could not listen on port");
      System.exit(1);
    }

    Socket clientSocket = null;
    while (active) {
      clientSocket = serverSocket.accept();
      EchoThread t = new EchoThread(Integer.toString(counter), clientSocket);
      nameList.add(t.getUsername());
      t.start();
      socketList.add(clientSocket.getOutputStream());
      userRelay();
      counter++;
    }

    serverSocket.close();
  }
Exemplo n.º 17
0
  public static void main(String[] args) throws IOException {
    sessions = new ArrayList<ATMServerThread>();
    Scanner userscanner = new Scanner(new FileInputStream("users.txt"));
    users = new ArrayList<User>();

    // Retrive user info from file and load them into the bank program.
    while (userscanner.hasNext()) {
      users.add(
          new User(
              userscanner.nextInt(),
              userscanner.nextInt(),
              userscanner.nextInt(),
              userscanner.nextInt()));
    }

    ServerSocket serverSocket = null;
    boolean listening = true;

    try {
      serverSocket = new ServerSocket(connectionPort);
    } catch (IOException e) {
      System.err.println("Could not listen on port: " + connectionPort);
      System.exit(1);
    }
    System.out.println("Bank started listening on port: " + connectionPort);

    // Start new thread to handle input in the bank console.
    new BankInputThread(motd).start();

    while (listening) {
      // Start a new session and add it to the list of sessions.
      // The list of users and the current MOTD is transfered to the new session-threads.
      sessions.add(new ATMServerThread(serverSocket.accept(), users, motd));
      sessions.get(sessions.size() - 1).start();
    }
    serverSocket.close();
  }
    protected Searcher(boolean _persistent, boolean _async) throws DeviceManagerException {

      try {
        int last_port = COConfigurationManager.getIntParameter("devices.tivo.net.tcp.port", 0);

        if (last_port > 0) {

          try {
            ServerSocket ss = new ServerSocket(last_port);

            ss.setReuseAddress(true);

            ss.close();

          } catch (Throwable e) {

            last_port = 0;
          }
        }

        twc = plugin_interface.getTracker().createWebContext(last_port, Tracker.PR_HTTP);

        tcp_port = twc.getURLs()[0].getPort();

        COConfigurationManager.setParameter("devices.tivo.net.tcp.port", tcp_port);

        twc.addPageGenerator(
            new TrackerWebPageGenerator() {
              public boolean generate(
                  TrackerWebPageRequest request, TrackerWebPageResponse response)
                  throws IOException {
                String id = (String) request.getHeaders().get("tsn");

                if (id == null) {

                  id = (String) request.getHeaders().get("tivo_tcd_id");
                }

                if (id != null && is_enabled) {

                  persistent = true;

                  DeviceTivo tivo =
                      foundTiVo(request.getClientAddress2().getAddress(), id, null, null);

                  return (tivo.generate(request, response));
                }

                return (false);
              }
            });

        control_socket = new DatagramSocket(null);

        control_socket.setReuseAddress(true);

        try {
          control_socket.setSoTimeout(60 * 1000);

        } catch (Throwable e) {
        }

        InetAddress bind = NetworkAdmin.getSingleton().getSingleHomedServiceBindAddress();

        control_socket.bind(new InetSocketAddress(bind, CONTROL_PORT));

        timer_event =
            SimpleTimer.addPeriodicEvent(
                "Tivo:Beacon",
                60 * 1000,
                new TimerEventPerformer() {
                  public void perform(TimerEvent event) {
                    if (!(manager_destroyed || search_destroyed)) {

                      sendBeacon();
                    }

                    // see if time to auto-shutdown searching

                    if (!persistent) {

                      synchronized (DeviceTivoManager.this) {
                        if (SystemTime.getMonotonousTime() - start >= LIFE_MILLIS) {

                          log("Terminating search, no devices found");

                          current_search = null;

                          destroy();
                        }
                      }
                    }
                  }
                });

        final AESemaphore start_sem = new AESemaphore("TiVo:CtrlListener");

        new AEThread2("TiVo:CtrlListener", true) {
          public void run() {
            start_sem.release();

            long successful_accepts = 0;
            long failed_accepts = 0;

            while (!(manager_destroyed || search_destroyed)) {

              try {
                byte[] buf = new byte[8192];

                DatagramPacket packet = new DatagramPacket(buf, buf.length);

                control_socket.receive(packet);

                successful_accepts++;

                failed_accepts = 0;

                if (receiveBeacon(packet.getAddress(), packet.getData(), packet.getLength())) {

                  persistent = true;
                }

              } catch (SocketTimeoutException e) {

              } catch (Throwable e) {

                if (control_socket != null && !search_destroyed && !manager_destroyed) {

                  failed_accepts++;

                  log("UDP receive on port " + CONTROL_PORT + " failed", e);
                }

                if ((failed_accepts > 100 && successful_accepts == 0) || failed_accepts > 1000) {

                  log("    too many failures, abandoning");

                  break;
                }
              }
            }
          }
        }.start();

        if (_async) {

          new DelayedEvent(
              "search:delay",
              5000,
              new AERunnable() {
                public void runSupport() {
                  sendBeacon();
                }
              });
        } else {

          start_sem.reserve(5000);

          sendBeacon();
        }

        log("Initiated device search");

      } catch (Throwable e) {

        log("Failed to initialise search", e);

        destroy();

        throw (new DeviceManagerException("Creation failed", e));
      }
    }
  public static void main(String[] args) throws IOException, InterruptedException {

    System.out.println("Auction Server starting");
    try { // Get hostname by textual representation of IP address
      InetAddress addr = InetAddress.getLocalHost(); // = InetAddress.getByName("127.0.0.1");
      String hostname = addr.getHostName(); // Get the host name
      System.out.println("ip address = " + addr.toString() + "\nHost name = " + hostname);
    } catch (UnknownHostException e) {
    }

    // used to let host user control flow of program
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    // System.out.println("How many players are needed?");
    int numPlayersNeeded = 2; // Integer.valueOf(br.readLine());

    // make an auction with which clients interact
    Auction myAuction = new Auction(5, numPlayersNeeded); // auction with 5 slots

    // SELECT TYPE OF AUCTION
    Vector<SimultaneousAscendingAuctionServerThread> myThreads =
        new Vector<SimultaneousAscendingAuctionServerThread>();

    ServerSocket serverSocket = null;
    int portNum = 7; // the luckiest port there is!
    // Try reading in the IP and socket number from the text file...
    try {
      BufferedReader in = new BufferedReader(new FileReader("./src/IP_and_Port.txt"));
      // two lines in this file.  First is hostName/IP address, and second is socket number of host
      String hName = in.readLine(); // use the hostname found above and skip this one
      portNum = Integer.valueOf(in.readLine());
      in.close();
    } catch (IOException e) {
    }

    try {
      serverSocket = new ServerSocket(portNum);
    } catch (IOException e) {
      System.err.println("AuctionServer could not listen on port: " + portNum + ".");
      System.exit(-1);
    }

    System.out.println("Clients should join the auction now...");
    boolean started = false;
    boolean firstThread = true; // used to designate first thread as "reporter"
    while (!started) { // (listening && !myAuction.isOver() ){

      SimultaneousAscendingAuctionServerThread aThread =
          new SimultaneousAscendingAuctionServerThread(
              serverSocket.accept(), myAuction, numPlayersNeeded);

      // set first thread as the "reporter", so only one copy of info printed to cmd prompt
      aThread.start();
      if (firstThread) {
        aThread.setReporter(true);
        firstThread = false;
      }

      myThreads.add(aThread);

      if (myThreads.size() >= numPlayersNeeded) {
        started = true;
        System.out.println("Auction should be ready to go...");
      } else
        System.out.println(
            "need more players.  Thread-count = "
                + myThreads.size()
                + "  , idCount = "
                + myAuction.bidderIDs.size());
      // myAuction was passed as a shallow copy... so only one auction exists
    }

    System.out.println("\nAuction has started with " + myThreads.size() + " agents!\n");

    // The auction is running right now... can you feel it?

    // System.out.println("Press Enter to end host connections and close...");
    // br.readLine();

    // System.out.println("Auction is complete... closing connections");
    for (int i = 0; i < myThreads.size(); i++) myThreads.get(i).join();

    for (int i = 0; i < myThreads.size(); i++)
      if (myThreads.get(i).isAlive()) myThreads.get(i).closeConnection();

    serverSocket.close();
  } // end main()
Exemplo n.º 20
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  public static void main(String[] args) throws IOException {
    boolean useArguments = false;
    Map config = null;

    try {
      yamlInstance = new Yaml();

      /*
       * Try to load configuration file
       */
      FileReader configFile = new FileReader(YAML_PATH + CONFIGURATION_FILE);
      config = (Map) yamlInstance.load(configFile);

    } catch (FileNotFoundException e) {
      System.out.println(
          "Could not load configuration file. Using program " + "arguments instead.");
      useArguments = true;
    }

    /* Scan for program arguments */
    int port = -1;
    try {

      if (useArguments) port = Integer.parseInt(args[0]);
      else
        // take the port number from the config file
        port = (Integer) config.get("port");

    } catch (ArrayIndexOutOfBoundsException e) {
      System.err.println("DungeonServer: specify a port to which to bind");
      System.out.println(usage());
      System.exit(1);
    }

    /* Attempt to bind to port */
    ServerSocket server = null;
    try {
      server = new ServerSocket(port);
    } catch (IOException e) {
      System.err.printf("DungeonServer: could not listen on port %d\n", port);
      System.exit(2);
    }

    System.out.printf("bound to port %d\n", port);

    System.out.println("loading universe:");

    /* Load universe */
    try {
      System.out.println("\tfinding universe file");

      FileReader universeFile = null;
      if (useArguments) universeFile = new FileReader(YAML_PATH + DEFAULT_UNIVERSE_FILE);
      else universeFile = new FileReader(YAML_PATH + config.get("world") + ".universe.yml");

      Object[] docs = new Object[3];
      Map<String, Object> preamble = null;
      Map<String, Map<String, Object>> rooms = null, items = null;

      try {
        System.out.println("\tchecking universe file");

        int i = 0;
        for (Object o : yamlInstance.loadAll(universeFile)) docs[i++] = o;

        preamble = (Map<String, Object>) docs[0];
        rooms = (Map<String, Map<String, Object>>) docs[1];
        items = (Map<String, Map<String, Object>>) docs[2];

        if (preamble == null || rooms == null || items == null) throw new NullPointerException();

      } catch (ArrayIndexOutOfBoundsException e) {
        System.err.println(
            "DungeonServer: error parsing universe " + "file: too many documents in universe file");
        System.exit(3);
      } catch (NullPointerException e) {
        System.err.println(
            "DungeonServer: error parsing universe " + "file: too few documents in universe file");
        System.exit(3);
      }

      /*
       * Used after parsing rooms to set universe parameters
       */
      boolean doWeather = false;
      String spawnRoomID = null;
      int timescale = -1;
      try {
        System.out.println("\treading preamble");

        /*
         * Load universe parameters from the preamble
         */
        doWeather = (Boolean) validateAndGet(preamble, "weather", Boolean.class);

        spawnRoomID = (String) validateAndGet(preamble, "spawn", String.class);

        timescale = (Integer) validateAndGet(preamble, "timescale", Integer.class);

      } catch (Exception e) {
        System.err.println("DungeonServer: failed parsing preamble (" + e.getMessage() + ")");
        System.exit(4);
      }

      /*
       * Loop through room definitions in universe file
       */

      /**
       * This hash map is used to resolve references from one room to another. Each time a room is
       * parsed, it is added to this map, and henceforth back references to the newly added room
       * will be resolved by checking this map.
       */
      HashMap<String, Room> knownRooms = new HashMap<String, Room>();

      /**
       * This list is maintained to easily check at the end of parsing if there are still references
       * to unseen rooms.
       */
      ArrayList<String> unseenRooms = new ArrayList<String>();

      /**
       * This is a list of triples (A, B, C) such that A is a room waiting for a reference to
       * another room, C, through a direction B. For A and B, the string ID of the rooms are used
       * (the same key used in the knownRooms hash map). This list is used whenever a room's exit
       * references cannot actually be resolved because the destination room has not yet been
       * parsed. At the end of parsing, as long as the unseenRooms list is empty, this list is
       * traversed to resolve the remaining references.
       */
      ArrayList<Triple<String, Direction, String>> unresolved;
      unresolved = new ArrayList<Triple<String, Direction, String>>();

      String thisRoomID = null;
      try {
        System.out.println("\tparsing rooms");

        for (Map.Entry<String, Map<String, Object>> m : rooms.entrySet()) {
          thisRoomID = m.getKey();
          Map<String, Object> thisMap = m.getValue();

          String roomName = (String) validateAndGet(thisMap, "name", String.class);

          String description = (String) validateAndGet(thisMap, "description", String.class);

          Hashtable<Pair<DayPart, Weather>, String> details;
          details = getDetails(thisMap);

          Room r = new Room(roomName, description, details);

          if (thisMap.containsKey("neverUseArticle")) {
            boolean neverUseArticle =
                (Boolean) validateAndGet(thisMap, "neverUseArticle", Boolean.class);

            r.setNeverUseArticle(neverUseArticle);
          }

          if (unseenRooms.contains(thisRoomID)) unseenRooms.remove(thisRoomID);

          knownRooms.put(thisRoomID, r);

          /*
           * Process exits out of this room
           */
          Map<String, String> exits = (Map) validateAndGet(thisMap, "exits", Map.class);

          for (Map.Entry<String, String> exit : exits.entrySet()) {
            String thisDirection = exit.getKey();
            String toRoomID = exit.getValue();

            /*
             * Verify the direction from the file
             */
            Direction dir;
            dir = Direction.fromString(thisDirection);
            if (dir == null) throw new InvalidDirectionException(thisDirection);

            /*
             * Look up the destination room in the hash map
             */
            if (knownRooms.containsKey(toRoomID)) r.addExit(dir, knownRooms.get(toRoomID));
            else {
              if (!unseenRooms.contains(toRoomID)) unseenRooms.add(toRoomID);

              Triple<String, Direction, String> t;
              t = new Triple<String, Direction, String>(thisRoomID, dir, toRoomID);
              unresolved.add(t);
            }
          }
        }
      } catch (Exception e) {
        System.err.println(
            "DungeonServer: failed parsing room '" + thisRoomID + "' (" + e.getMessage() + ")");
        System.exit(4);
      }

      if (!unseenRooms.isEmpty()) throw new UnresolvedReferenceException(unseenRooms);

      /*
       * Invariant: There were no references to undefined rooms in the
       * file. Invariant: All the rooms in the file have been
       * instantiated.
       *
       * All rooms in the universe file have been parsed, but there may
       * still be exits waiting to be added because their destination was
       * not yet parsed at the time. Now loop through the unresolved list
       * to set them up.
       */
      for (Triple<String, Direction, String> t : unresolved) {
        Room fromRoom = knownRooms.get(t.first);
        Room toRoom = knownRooms.get(t.third);
        Direction dir = t.second;

        fromRoom.addExit(dir, toRoom);
      }

      /*
       * Invariant: All exits in the file have been set up among the
       * rooms.
       */

      Room spawnRoom = knownRooms.get(spawnRoomID);
      universe = new DungeonUniverse(spawnRoom, doWeather, timescale, knownRooms.values());

      universeFile.close();

    } catch (Exception e) {
      System.err.println("DungeonServer: failed loading universe " + "(" + e.getMessage() + ")");
      System.exit(2);
    }

    System.out.println("loaded universe");

    /* Start narrator */
    try {
      narrator = new DungeonNarrator();
    } catch (Exception e) {
      System.err.println("DungeonServer: failed starting narrator");
      System.exit(3);
    }

    System.out.println("started narrator");

    /* Start the game tick */
    try {
      tick = new DungeonGameTick();
      tick.start();
    } catch (Exception e) {
      System.err.println("DungeonServer: failed starting game tick");
      System.exit(3);
    }

    System.out.println("started game tick");

    /* Start accepting events */
    try {
      events = new DungeonDispatcher();
      events.start();
    } catch (Exception e) {
      System.err.println("DungeonServer: failed starting event queue");
      System.exit(3);
    }

    System.out.println("started event queue");

    /* Listen for clients */
    try {
      System.out.println("listening for clients");

      while (true) new DungeonConnectionThread(server.accept()).start();
    } catch (IOException e) {
      System.err.printf("DungeonServer: failed accepting client on port %d\n", port);
      System.exit(2);
    } finally {
      server.close();
    }
  }
Exemplo n.º 21
0
  // ------------------------------------
  // main
  // ------------------------------------
  public static void main(String argv[]) throws Exception {
    // create a Server object
    Server theServer = new Server();

    // show GUI:
    theServer.pack();
    theServer.setVisible(true);

    // get RTSP socket port from the command line
    int RTSPport = Integer.parseInt(argv[0]);

    // Initiate TCP connection with the client for the RTSP session
    ServerSocket listenSocket = new ServerSocket(RTSPport);
    theServer.RTSPsocket = listenSocket.accept();
    listenSocket.close();

    // Get Client IP address
    theServer.ClientIPAddr = theServer.RTSPsocket.getInetAddress();

    // Initiate RTSPstate
    state = INIT;

    // Set input and output stream filters:
    RTSPBufferedReader =
        new BufferedReader(new InputStreamReader(theServer.RTSPsocket.getInputStream()));
    RTSPBufferedWriter =
        new BufferedWriter(new OutputStreamWriter(theServer.RTSPsocket.getOutputStream()));

    // Wait for the SETUP message from the client
    int request_type;
    boolean done = false;
    while (!done) {
      request_type = theServer.parse_RTSP_request(); // blocking

      if (request_type == SETUP) {
        done = true;

        // update RTSP state
        state = READY;
        System.out.println("New RTSP state: READY");

        // Send response
        theServer.send_RTSP_response();

        // init the VideoStream object:
        theServer.video = new VideoStream(VideoFileName);

        // init RTP socket
        theServer.RTPsocket = new DatagramSocket();
      }
    }

    // loop to handle RTSP requests
    while (true) {
      // parse the request
      request_type = theServer.parse_RTSP_request(); // blocking

      if ((request_type == PLAY) && (state == READY)) {
        // send back response
        theServer.send_RTSP_response();
        // start timer
        theServer.timer.start();
        // update state
        state = PLAYING;
        System.out.println("New RTSP state: PLAYING");
      } else if ((request_type == PAUSE) && (state == PLAYING)) {
        // send back response
        theServer.send_RTSP_response();
        // stop timer
        theServer.timer.stop();
        // update state
        state = READY;
        System.out.println("New RTSP state: READY");
      } else if (request_type == TEARDOWN) {
        // send back response
        theServer.send_RTSP_response();
        // stop timer
        theServer.timer.stop();
        // close sockets
        theServer.RTSPsocket.close();
        theServer.RTPsocket.close();

        System.exit(0);
      }
    }
  }