private void handleKeepAlive() {
   Connection c = null;
   try {
     netCode = ois.readInt();
     c = checkConnectionNetCode();
     if (c != null && c.getState() == Connection.STATE_CONNECTED) {
       oos.writeInt(ACK_KEEP_ALIVE);
       oos.flush();
       System.out.println("->ACK_KEEP_ALIVE"); // $NON-NLS-1$
     } else {
       System.out.println("->NOT_CONNECTED"); // $NON-NLS-1$
       oos.writeInt(NOT_CONNECTED);
       oos.flush();
     }
   } catch (IOException e) {
     System.out.println("handleKeepAlive: " + e.getMessage()); // $NON-NLS-1$
     if (c != null) {
       c.setState(Connection.STATE_DISCONNECTED);
       System.out.println(
           "Connection closed with "
               + c.getRemoteAddress()
               + //$NON-NLS-1$
               ":"
               + c.getRemotePort()); // $NON-NLS-1$
     }
   }
 }
 private void handleConnect() {
   try {
     int program_version = ois.readInt();
     port = ois.readInt();
     address = listenSocket.getInetAddress();
     netCode = ois.readInt();
     Connection c = checkConnectionNetCode();
     if (c != null) {
       oos.writeInt(ALREADY_CONNECTED);
       oos.flush();
       System.out.println("->ALREADY_CONNECTED"); // $NON-NLS-1$
     } else {
       if (isAcceptingConnections()) {
         if (connections.size() < Utils.getMAX_CONNECTIONS()) {
           if (Utils.VERSION == program_version) {
             Connection newConnection = newConnection();
             if (newConnection != null) {
               oos.writeInt(CONNECTED);
               newConnection.setState(Connection.STATE_CONNECTED);
               System.out.println("->CONNECTED"); // $NON-NLS-1$
             } else {
               oos.writeInt(ALREADY_CONNECTED);
               System.out.println("->ALREADY_CONNECTED"); // $NON-NLS-1$
             }
             oos.flush();
           } else {
             oos.writeInt(INCOMPATIBLE_PROGRAM_VERSION);
             oos.flush();
             System.out.println("->INCOMPATIBLE_PROGRAM_VERSION"); // $NON-NLS-1$
           }
         } else {
           oos.writeInt(TOO_MANY_CONNECTIONS);
           oos.flush();
           System.out.println("->TOO_MANY_CONNECTIONS"); // $NON-NLS-1$
         }
       } else {
         oos.writeInt(NOT_ACCEPTING_CONNECTIONS);
         oos.flush();
         System.out.println("->NOT_ACCEPTING_CONNECTIONS"); // $NON-NLS-1$
       }
     }
   } catch (IOException ex) {
     System.out.println(ex.getMessage());
   }
 }
 @Override
 public void run() {
   isActive = true;
   try {
     serverSocket = new ServerSocket(Utils.getLOCAL_PORT());
     notifyStatusListeners(
         Messages.getInstance()
             .getString(
                 "T_NET_SERVER_LISTENING_ON_PORT",
                 Integer.toString(Utils.getLOCAL_PORT()))); // $NON-NLS-1$
   } catch (IOException e) {
     if (e instanceof BindException) {
       notifyStatusListeners(
           Messages.getInstance()
               .getString(
                   "T_PORT_ALREADY_IN_USE",
                   Integer.toString(Utils.getLOCAL_PORT()))); // $NON-NLS-1$
     } else e.printStackTrace();
     isActive = false;
   }
   while (isActive) {
     try {
       listenSocket = serverSocket.accept();
       ois = new ObjectInputStream(listenSocket.getInputStream());
       oos = new ObjectOutputStream(listenSocket.getOutputStream());
       receivedMessage = ois.readInt();
       System.out.println(messageToString(receivedMessage));
       switch (receivedMessage) {
         case CONNECT:
           handleConnect();
           break;
         case SEND_CODE:
           handleSendCode();
           break;
         case KEEP_ALIVE:
           handleKeepAlive();
           break;
         case DISCONNECT:
           handleDisconnect();
           break;
       }
       ois.close();
       oos.close();
     } catch (IOException e) {
       System.out.println(e.getMessage());
     } finally {
       if (listenSocket != null)
         try {
           listenSocket.close();
         } catch (IOException e) {
           e.printStackTrace();
         }
     }
   }
 }
  private void handleSendCode() {
    Connection c = null;
    GeneticCode code;

    try {
      netCode = ois.readInt();
      c = checkConnectionNetCode();
      if (c != null && c.getState() == Connection.STATE_CONNECTED) {
        oos.writeInt(WAITING_CODE);
        oos.flush();
        System.out.println("->WAITING_CODE"); // $NON-NLS-1$
        code = (GeneticCode) ois.readObject();
        System.out.println("Genetic code"); // $NON-NLS-1$
        oos.writeInt(CODE_RECEIVED);
        oos.flush();
        System.out.println("->CODE_RECEIVED"); // $NON-NLS-1$
        c.getInCorridor().receiveOrganism(code);
      } else {
        System.out.println("->NOT_CONNECTED"); // $NON-NLS-1$
        oos.writeInt(NOT_CONNECTED);
        oos.flush();
      }
    } catch (IOException e) {
      System.out.println("handleSendCode: " + e.getMessage()); // $NON-NLS-1$
      if (c != null) {
        c.setState(Connection.STATE_DISCONNECTED);
        System.out.println(
            "Connection closed with "
                + c.getRemoteAddress()
                + //$NON-NLS-1$
                ":"
                + c.getRemotePort()); // $NON-NLS-1$
      }
    } catch (ClassNotFoundException e) {
      System.out.println("handleSendCode: " + e.getMessage()); // $NON-NLS-1$
      if (c != null) {
        c.setState(Connection.STATE_DISCONNECTED);
        System.out.println(
            "Connection closed with "
                + c.getRemoteAddress()
                + //$NON-NLS-1$
                ":"
                + c.getRemotePort()); // $NON-NLS-1$
      }
    }
  }
Пример #5
0
  public void actionPerformed(ActionEvent e) {

    if (e.getSource() == butConnect) {
      try {
        boolean ok = serverConnection();
        if (ok) {
          setInitPanel();
        } else {
          System.out.println("Le pseudo existe déjà, choisissez en un autre.");
        }
      } catch (IOException err) {
        System.err.println(
            "Problème de connection avec le serveur: " + err.getMessage() + "\n.Arrêt...");
        System.exit(1);
      }
    } else if (e.getSource() == butListParty) {
      try {
        // envoyer requête LIST PARTY
        oos.writeInt(JungleServer.REQ_LISTPARTY);
        oos.flush();

        // recevoir résultat et l'afficher dans textInfoInit
        System.out.println("flush");
        boolean pret = ois.readBoolean();
        System.out.println(pret);
        if (pret) {
          String nomParty = (String) ois.readObject();
          System.out.println("apres read");
          textInfoInit.append(nomParty + " ");
        }

      } catch (ClassNotFoundException err) {
      } catch (IOException err) {
        System.err.println(
            "Problème de connection avec le serveur: " + err.getMessage() + "\n.Arrêt...");
        System.exit(1);
      }

    } else if (e.getSource() == butCreateParty) {
      try {
        boolean ok;
        // envoyer requête CREATE PARTY (paramètres : nom partie et nb joueurs nécessaires)
        oos.writeInt(JungleServer.REQ_CREATEPARTY);
        oos.writeObject(textCreate.getText());
        int nbJoueurs = (Integer) spinNbPlayer.getValue();
        oos.writeInt(nbJoueurs);
        oos.flush();
        // recevoir résultat -> ok
        ok = ois.readBoolean();
        System.out.println(ok);
        // si ok == true :
        if (ok) {
          // mettre le panneau party au centre
          setPartyPanel();
          // afficher un message dans textInfoParty comme quoi il faut attendre le début de partie
          textInfoParty.append("Attendre le début de la partie");
          // créer un ThreadClient et lancer son exécution
          ThreadClient threadClient = new ThreadClient(this);
          threadClient.start();
        }
      } catch (IOException err) {
        System.err.println(
            "probleme de connection serveur : " + err.getMessage() + "\n.Aborting...");
        System.exit(1);
      }
    } else if (e.getSource() == butJoinParty) {

      try {
        int idPlayer;
        // envoyer requête JOIN PARTY (paramètres : numero partie)
        oos.writeInt(JungleServer.REQ_JOINPARTY);
        oos.flush();
        System.out.println("requete envoyée");
        int numPartie = Integer.parseInt(textJoin.getText());
        oos.writeInt(numPartie);
        oos.flush();
        System.out.println("numPartie flushé");
        // recevoir résultat -> idPlayer
        idPlayer = ois.readInt();
        System.out.println("idplayer reçu : " + idPlayer);
        // si idPlayer >= 1 :
        if (idPlayer >= 1) {
          // mettre le panneau party au centre
          setPartyPanel();
          // afficher un message dans textInfoParty comme quoi il faut attendre le début de partie
          textInfoParty.append("Attendre la début de la partie");
          // créer un ThreadClient et lancer son exécution
          System.out.println("avant démarrage du thread");
          ThreadClient threadClient = new ThreadClient(this);
          threadClient.start();
          System.out.println("Apres le thread");
        }
      } catch (IOException err) {
        System.err.println("Problème de connection serveur: " + err.getMessage() + "\n.Arrêt...");
        System.exit(1);
      }
    } else if (e.getSource() == butPlay) {
      try {
        // envoyer requête PLAY (paramètre : contenu de textPlay)
        oos.writeInt(JungleServer.REQ_PLAY);
        oos.writeObject(textPlay.getText());
        oos.flush();
        orderSent = true;
        butPlay.setEnabled(false);
        textPlay.setEnabled(false);

        // mettre orderSent à true
        // bloquer le bouton play et le textfiled associé
      } catch (IOException err) {
        System.err.println("Problème connection serveur: " + err.getMessage() + "\n.Arrêt...");
        System.exit(1);
      }
    } else if (e.getSource() == butQuit) {
      try {
        oos.close();
        ois.close();
        setConnectionPanel();
        comm = null;
      } catch (IOException err) {
        System.err.println("Problème connection serveur: " + err.getMessage() + "\n.Arrêt...");
        System.exit(1);
      }
    }
  }
    public synchronized void run() {
      int messageType;
      String buf;
      PaintMessage paint;
      int j, k, num, tmp;
      boolean state = true;

      try {
        readyState[id - 1] = 0; // 进入等待房间
        broadcast(4, players);
        // 当前客户端叫什么名字
        /*remoteOut.writeInt(12);
        remoteOut.flush();
        remoteOut.writeUnshared(name);*/
        // 大家的名字和等待状态
        /*broadcast(4,players);
        broadcast(9,readyState);*/

        while (state) {
          messageType = remoteIn.readInt();
          switch (messageType) {
            case 1: // 画板上画的像素点
              {
                paint = (PaintMessage) remoteIn.readUnshared();
                broadcast(1, paint);
                break;
              }
            case 2: // 聊天框中内容
              {
                buf = (String) remoteIn.readUnshared();
                if (buf.equals(title.getKey() + "\n")
                    && id != title.getId()
                    && right[id - 1] == 0) {
                  System.out.println(port + ":" + buf);
                  buf = "(**回答正确**)\n";
                  right[id - 1] = 1;
                  if (first == 0) { // 第一个人答对
                    scores[id - 1] += 2;
                    scores[title.getId() - 1] += 3;
                    first = 1;
                  } else { // 非第一个答对的,画的与猜的各加1分
                    scores[id - 1] += 1;
                    scores[title.getId() - 1] += 1;
                  }
                  // 要重发成绩
                  broadcast(11, scores);
                } else if (buf.equals(title.getKey() + "\n")
                    && id != title.getId()
                    && right[id - 1] == 1) buf = "(*@#$*/%(*!)\n";
                if (buf.equals(title.getKey() + "\n") && id == title.getId())
                  buf = "(*@#$*/%(*!)\n";
                SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
                buf = "[" + df.format(new Date()) + "]" + players[id - 1] + ":" + buf;
                broadcast(2, buf);

                for (j = 0; j <= 5; j++) {
                  if (readyState[j] != -1 && right[j] == 0 && j != (title.getId() - 1)) break;
                }
                if (j > 5) // 大家都已经答对了
                countOver = true;

                break;
              }
            case 5: // 清屏
              broadcast(5);
              break;
            case 7: // 等待界面,当前用户准备
              {
                readyState[id - 1] = 1;
                // 检测是否能开始
                for (j = 0, num = 0, k = 0; j <= 5; j++) {
                  if (readyState[j] != -1) num++; // 统计等待房间内人数
                  if (readyState[j] == 0) k++; // 统计没准备的人数
                }
                if (num >= 2 && k == 0) // 可以开始了
                readyState[6] = 1;
                // 传一下准备状态
                broadcast(9, readyState);

                if (readyState[6] == 1) {
                  // 大家的名字
                  broadcast(4, players);
                  System.out.println("游戏开始!");

                  CountDownSem.release(); // 开始倒计时
                }
                break;
              }
            case 8: // 等待界面,当前用户退出
              {
                readyState[id - 1] = -1;
                players[id - 1] = "虚位以待";
                System.out.println("端口号" + port + "的玩家退出了房间");

                state = false;
                broadcast(4, players);
                clients.removeElement(remoteOut);

                // 再检测一下是否符合开始条件
                for (j = 0, num = 0, k = 0; j <= 5; j++) {
                  if (readyState[j] != -1) num++; // 统计等待房间内人数
                  if (readyState[j] == 0) k++; // 统计没准备的人数
                }
                if (num >= 2 && k == 0) // 可以开始了
                readyState[6] = 1;
                // 传一下准备状态
                broadcast(9, readyState);
                if (readyState[6] == 1) {
                  // 大家的名字
                  broadcast(4, players);
                  System.out.println("游戏开始!");

                  CountDownSem.release(); // 开始倒计时
                }
                break;
              }
            case 12: // 传入用户输入的昵称
              name = (String) remoteIn.readUnshared();
              players[id - 1] = name;
              broadcast(4, players);
              broadcast(9, readyState);
              break;
              // case n+1
          }
        }
      } catch (Exception e) {
        System.out.println(e.getMessage() + ": 端口为" + port + "的玩家退出了游戏。。");
        players[id - 1] = "虚位以待";
        readyState[id - 1] = -1;
        scores[id - 1] = 0;
        for (tmp = 0; tmp <= 5; tmp++) { // 判断是不是最后一个人
          if (readyState[tmp] != -1) break;
        }
        if (tmp > 5) readyState[6] = 0;
        String s = name + "离开了房间。。。\n";
        broadcast(2, s);
        broadcast(4, players);
        broadcast(11, scores);
        clients.removeElement(remoteOut);
        if (id == title.getId()) // 画的人退出了
        countOver = true;
      }
    }
  /** The run method. */
  public void run() {
    instances.add(this);
    try {
      listener.startUnpack();
      String currentOs = System.getProperty("os.name").toLowerCase();
      //
      // Initialisations
      FileOutputStream out = null;
      ArrayList parsables = new ArrayList();
      ArrayList executables = new ArrayList();
      List packs = idata.selectedPacks;
      int npacks = packs.size();
      udata = UninstallData.getInstance();

      // Specific to the web installers
      if (idata.kind.equalsIgnoreCase("web") || idata.kind.equalsIgnoreCase("web-kunststoff")) {
        InputStream kin = getClass().getResourceAsStream("/res/WebInstallers.url");
        BufferedReader kreader = new BufferedReader(new InputStreamReader(kin));
        jarLocation = kreader.readLine();
      }

      // We unpack the selected packs
      for (int i = 0; i < npacks; i++) {
        // We get the pack stream
        int n = idata.allPacks.indexOf(packs.get(i));
        ObjectInputStream objIn = new ObjectInputStream(getPackAsStream(n));

        // We unpack the files
        int nfiles = objIn.readInt();
        listener.changeUnpack(0, nfiles, ((Pack) packs.get(i)).name);
        for (int j = 0; j < nfiles; j++) {
          // We read the header
          PackFile pf = (PackFile) objIn.readObject();
          if (null == pf.os || matchOS(currentOs, pf.os.toLowerCase())) {
            // We translate & build the path
            String path = translatePath(pf.targetPath);
            File pathFile = new File(path);
            String fname = pathFile.getName();
            int z = fname.length();
            File dest = pathFile.getParentFile();
            if (!dest.exists()) dest.mkdirs();

            // We add the path to the log,
            udata.addFile(path);

            listener.progressUnpack(j, path);

            // if this file exists and shouldnot override skip this file
            if (((pf.override == false) && (pathFile.exists()))) {
              objIn.skip(pf.length);
              continue;
            }

            // We copy the file
            out = new FileOutputStream(path);
            byte[] buffer = new byte[5120];
            long bytesCopied = 0;
            while (bytesCopied < pf.length) {
              int maxBytes =
                  (pf.length - bytesCopied < buffer.length
                      ? (int) (pf.length - bytesCopied)
                      : buffer.length);
              int bytesInBuffer = objIn.read(buffer, 0, maxBytes);
              if (bytesInBuffer == -1) throw new IOException("Unexpected end of stream");

              out.write(buffer, 0, bytesInBuffer);

              bytesCopied += bytesInBuffer;
            }
            // Cleanings
            out.close();

            // Empty dirs restoring
            String _n = pathFile.getName();
            if (_n.startsWith("izpack-keepme") && _n.endsWith(".tmp")) pathFile.delete();

          } else objIn.skip(pf.length);
        }

        // Load information about parsable files
        int numParsables = objIn.readInt();
        int k;
        for (k = 0; k < numParsables; k++) {
          ParsableFile pf = (ParsableFile) objIn.readObject();
          pf.path = translatePath(pf.path);
          parsables.add(pf);
        }

        // Load information about executable files
        int numExecutables = objIn.readInt();
        for (k = 0; k < numExecutables; k++) {
          ExecutableFile ef = (ExecutableFile) objIn.readObject();
          ef.path = translatePath(ef.path);
          if (null != ef.argList && !ef.argList.isEmpty()) {
            String arg = null;
            for (int j = 0; j < ef.argList.size(); j++) {
              arg = (String) ef.argList.get(j);
              arg = translatePath(arg);
              ef.argList.set(j, arg);
            }
          }
          executables.add(ef);
          if (ef.executionStage == ExecutableFile.UNINSTALL) {
            udata.addExecutable(ef);
          }
        }
        objIn.close();
      }

      // We use the scripts parser
      ScriptParser parser = new ScriptParser(parsables, vs);
      parser.parseFiles();

      // We use the file executor
      FileExecutor executor = new FileExecutor(executables);
      if (executor.executeFiles(ExecutableFile.POSTINSTALL) != 0)
        javax.swing.JOptionPane.showMessageDialog(
            null,
            "The installation was not completed.",
            "Installation warning",
            javax.swing.JOptionPane.WARNING_MESSAGE);

      // We put the uninstaller
      putUninstaller();

      // The end :-)
      listener.stopUnpack();
    } catch (Exception err) {
      listener.stopUnpack();
      listener.errorUnpack(err.toString());
    }
    instances.remove(instances.indexOf(this));
  }