Exemplo n.º 1
0
 protected void listen(Socket socket) {
   SocketHandler handler = getHandler();
   // 处理请求
   try {
     handler.handle(socket);
   }
   // 仅仅是关闭连接
   catch (SocketClosed e) {
   }
   // 停止服务
   catch (ServerStopped e) {
     stop = true;
   }
   // 处理异常
   catch (Throwable e) {
     handler.whenError(socket, e);
   }
   // 确保关闭
   finally {
     if (!socket.isClosed())
       try {
         socket.close();
       } catch (IOException e) {
         throw Lang.wrapThrow(e);
       }
   }
 }
Exemplo n.º 2
0
 @Override
 public void run() {
   try {
     while (true) {
       if (!socket.isConnected()) {
         log.info("socket disconnected");
         break;
       }
       if (!handler.handleSocket(socket)) {
         log.info("server released client socket");
         socket.close();
         break;
       }
     }
   } catch (Exception ex) {
     log.warn(ex.toString());
   }
 }
Exemplo n.º 3
0
  /**
   * @param args is used to define all the options of the client. <port:N> is used to specify the
   *     port for the connection (default is 3001) <host:ADDRESS> is used to specify the address of
   *     the host where the server is running (default is localhost) <id:ClientID> is used to
   *     specify the ID of the client sent to the server (default is championship2009) <verbose:on>
   *     is used to set verbose mode on (default is off) <maxEpisodes:N> is used to set the number
   *     of episodes (default is 1) <maxSteps:N> is used to set the max number of steps for each
   *     episode (0 is default value, that means unlimited number of steps) <stage:N> is used to set
   *     the current stage: 0 is WARMUP, 1 is QUALIFYING, 2 is RACE, others value means UNKNOWN
   *     (default is UNKNOWN) <trackName:name> is used to set the name of current track
   */
  public static void main(String[] args) {
    parseParameters(args);
    SocketHandler mySocket = new SocketHandler(host, port, verbose);
    String inMsg;

    Controller driver = load(args[0]);
    driver.setStage(stage);
    driver.setTrackName(trackName);

    /* Build init string */
    float[] angles = driver.initAngles();
    String initStr = clientId + "(init";
    for (int i = 0; i < angles.length; i++) {
      initStr = initStr + " " + angles[i];
    }
    initStr = initStr + ")";

    long curEpisode = 0;
    boolean shutdownOccurred = false;
    do {

      /*
       * Client identification
       */

      do {
        mySocket.send(initStr);
        inMsg = mySocket.receive(UDP_TIMEOUT);
      } while (inMsg == null || inMsg.indexOf("***identified***") < 0);

      /*
       * Start to drive
       */
      long currStep = 0;
      while (true) {
        /*
         * Receives from TORCS the game state
         */
        inMsg = mySocket.receive(UDP_TIMEOUT);

        if (inMsg != null) {

          /*
           * Check if race is ended (shutdown)
           */
          if (inMsg.indexOf("***shutdown***") >= 0) {
            shutdownOccurred = true;
            System.out.println("Server shutdown!");
            break;
          }

          /*
           * Check if race is restarted
           */
          if (inMsg.indexOf("***restart***") >= 0) {
            driver.reset();
            if (verbose) System.out.println("Server restarting!");
            break;
          }

          Action action = new Action();
          if (currStep < maxSteps || maxSteps == 0)
            action = driver.control(new MessageBasedSensorModel(inMsg));
          else action.restartRace = true;

          currStep++;
          mySocket.send(action.toString());
        } else System.out.println("Server did not respond within the timeout");
      }

    } while (++curEpisode < maxEpisodes && !shutdownOccurred);

    /*
     * Shutdown the controller
     */
    driver.shutdown();
    mySocket.close();
    System.out.println("Client shutdown.");
    System.out.println("Bye, bye!");
  }
Exemplo n.º 4
0
 public void Connect() {
   socketHandler =
       new SocketHandler(ctx, motorHandler.getMotorFirst(), motorHandler.getMotorSecond());
   socketHandler.execute("");
 }
Exemplo n.º 5
0
    @Override
    public void run() {
      System.out.println("Starting SocketHandler");
      if (!handlerQueue.isEmpty()) {
        System.out.println("found " + handlerQueue.size() + " SocketHandler objects");
        ArrayList<SocketHandler> local = new ArrayList<SocketHandler>(); // Local copy for timer

        Iterator<SocketHandler> i = handlerQueue.iterator(); // Clone queue
        while (i.hasNext()) {
          local.add(i.next());
        }

        handlerQueue.clear(); // Clear queue
        System.out.println(
            "Cleared queue to "
                + handlerQueue.size()
                + " and local copy filled to "
                + local.size());

        if (!local.isEmpty()) {
          for (SocketHandler sh : local) { // Parse local queue
            String response = "NULL";

            try {

              ObjectInputStream objectInputStream = null;
              ObjectOutputStream objectOutputStream = null;

              try {
                objectInputStream = new ObjectInputStream(sh.getSocket().getInputStream());
                objectOutputStream = new ObjectOutputStream(sh.getSocket().getOutputStream());
              } catch (Exception e) {
                e.printStackTrace();
                System.out.println("Error creating streams!");
                if (objectInputStream != null) objectInputStream.close();
                if (objectOutputStream != null) objectOutputStream.close();
                if (sh.getSocket() != null) sh.getSocket().close();
                return;
              }

              String line = (String) objectInputStream.readObject();

              if (line == null) return;

              ArrayList<String> requestLines =
                  new ArrayList<String>(Arrays.asList(line.split("\n")));

              if (requestLines.size() == 0 || requestLines.get(0).equals("")) {
                // TODO: Bad requestLines page
                // KingdomsDaemon.getInstance().getUtils().logLine(LogType.ERROR, "Bad requestLines
                // from client. No data found!");
                return;
              }

              PayloadType type = PayloadType.valueOf(requestLines.get(0));
              if (type == PayloadType.PLAYER_KINGDOMS_LIST) {
                PlayerKingdomsListPayload payload =
                    KingdomsDaemon.getInstance()
                        .gson
                        .fromJson(requestLines.get(1), PlayerKingdomsListPayload.class);
                StatusPlayerKingdomsList out = new StatusPlayerKingdomsList();
                if (KingdomsDaemon.getInstance().hasKingdom(payload.player.playerUUID)) {
                  out.setHasKingdom(true);
                  out.setPlayerKingdomsList(
                      KingdomsDaemon.getInstance().getPlayerKingdoms(payload.player));
                } else {
                  out.setHasKingdom(false);
                }
                response = KingdomsDaemon.getInstance().gson.toJson(out);
              } else if (type == PayloadType.SAMPLE_KINGDOMS_LIST) {
                response =
                    KingdomsDaemon.getInstance()
                        .gson
                        .toJson(
                            new StatusSampleList()
                                .setSampleList(KingdomsDaemon.getInstance().getSampleKingdoms()));
              } else if (type == PayloadType.CREATE) {
                CreatePayload payload =
                    KingdomsDaemon.getInstance()
                        .gson
                        .fromJson(requestLines.get(1), CreatePayload.class);
                Kingdom kingdom =
                    new Kingdom(
                        payload.owner,
                        payload.sample,
                        KingdomsDaemon.getInstance().getPlayerKingdoms(payload.owner).size());
                kingdom.setName(payload.name);
                FileUtil.installKingdom(kingdom);
                KingdomsDaemon.getInstance().insertKingdomInDatabase(kingdom);
              } else if (type == PayloadType.RESET) {
                ResetPayload payload =
                    KingdomsDaemon.getInstance()
                        .gson
                        .fromJson(requestLines.get(1), ResetPayload.class);
                FileUtil.resetKingdom(payload.kingdom);
                KingdomsDaemon.getInstance().insertKingdomInDatabase(payload.kingdom);
              } else if (type == PayloadType.RENAME) {
                RenamePayload payload =
                    KingdomsDaemon.getInstance()
                        .gson
                        .fromJson(requestLines.get(1), RenamePayload.class);
                Kingdom kd = KingdomsDaemon.getInstance().getKingdom(payload.getOldName());
                kd.setName(payload.getNewName());
                FileUtil.renameKingdom(kd);
                KingdomsDaemon.getInstance().changeKingdomNameInDatabase(payload.getOldName(), kd);
              } else if (type == PayloadType.START) {
                StartPayload payload =
                    KingdomsDaemon.getInstance()
                        .gson
                        .fromJson(requestLines.get(1), StartPayload.class);
                if (KingdomsDaemon.getInstance().getServers().size() > 70) {
                  response = "KINGDOMS_FULL";
                } else {
                  int port = KingdomsDaemon.getInstance().getFreePort();
                  if (port != -1) {
                    response = "{port:" + port + "}";
                    KingdomsDaemon.getInstance()
                        .addKingdomServer(new KingdomServer(payload.kingdom, port));
                  }
                }
              } else if (type == PayloadType.STOP) {
                StopPayload payload =
                    KingdomsDaemon.getInstance()
                        .gson
                        .fromJson(requestLines.get(1), StopPayload.class);
                KingdomsDaemon.getInstance()
                    .getServer(KingdomsDaemon.getInstance().getKingdom(payload.kingdomName))
                    .setState(ServerState.SHUTDOWN);
                // TODO: Remove from database of active servers if needed.
              } else if (type == PayloadType.KINGDOM_DATA) {
                KingdomDataPayload payload =
                    KingdomsDaemon.getInstance()
                        .gson
                        .fromJson(requestLines.get(1), KingdomDataPayload.class);
                if (payload.dataType == KingdomDataType.STARTUP) {
                  KingdomServer server = KingdomsDaemon.getInstance().getServer(payload.kingdom);
                  if (server != null) {
                    response = server.startup;
                  } else {
                    response = "offline";
                  }
                } else if (payload.dataType == KingdomDataType.MOTD) {
                  response = FileUtil.getKingdomMOTD(payload.kingdom);
                }
              } else if (type == PayloadType.MODIFY_MOTD) {
                ModifyMOTDPayload payload =
                    KingdomsDaemon.getInstance()
                        .gson
                        .fromJson(requestLines.get(1), ModifyMOTDPayload.class);
                FileUtil.editKingdomMOTD(payload.getKingdom(), payload.getMOTD());
              }
              if (type == PayloadType.KINGDOM) {
                KingdomPayload payload =
                    KingdomsDaemon.getInstance()
                        .gson
                        .fromJson(requestLines.get(1), KingdomPayload.class);
                if (KingdomsDaemon.getInstance().isKingdom(payload.kingdomName)) {
                  response =
                      KingdomsDaemon.getInstance()
                          .gson
                          .toJson(KingdomsDaemon.getInstance().getKingdom(payload.kingdomName));
                } else {
                  response = "null";
                }
              } else if (type == PayloadType.ADDON) {
                AddonPayload payload =
                    KingdomsDaemon.getInstance()
                        .gson
                        .fromJson(requestLines.get(1), AddonPayload.class);
                if (payload.addonPayloadType == AddonPayloadType.INSTALL) {
                  FileUtil.installAddon(payload.kingdom, payload.addon);
                } else if (payload.addonPayloadType == AddonPayloadType.REMOVE) {
                  FileUtil.removeAddon(payload.kingdom, payload.addon);
                } else if (payload.addonPayloadType == AddonPayloadType.UPDATE) {
                  FileUtil.removeAddon(payload.kingdom, payload.addon);
                  FileUtil.installAddon(payload.kingdom, payload.addon);
                }
              } else if (type == PayloadType.ADDON_LIST) {
                response =
                    KingdomsDaemon.getInstance()
                        .gson
                        .toJson(KingdomsDaemon.getInstance().getAddons());
              }

              objectOutputStream.writeObject(response);

              if (objectInputStream != null) objectInputStream.close();
              if (objectOutputStream != null) objectOutputStream.close();

            } catch (Exception e) {
              e.printStackTrace();
            }

            if (sh.getSocket() != null) {
              try {
                sh.getSocket().close();
              } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              }
            }
          }
        }
      }

      try {
        Thread.sleep(50);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }