コード例 #1
0
  private static void checkAttributesSanity(
      final int attributeRecordId,
      final IntArrayList usedAttributeRecordIds,
      final IntArrayList validAttributeIds)
      throws IOException {
    assert !usedAttributeRecordIds.contains(attributeRecordId);
    usedAttributeRecordIds.add(attributeRecordId);

    final DataInputStream dataInputStream = getAttributesStorage().readStream(attributeRecordId);
    try {
      while (dataInputStream.available() > 0) {
        int attId = DataInputOutputUtil.readINT(dataInputStream);
        int attDataRecordId = DataInputOutputUtil.readINT(dataInputStream);
        assert !usedAttributeRecordIds.contains(attDataRecordId);
        usedAttributeRecordIds.add(attDataRecordId);
        if (!validAttributeIds.contains(attId)) {
          assert getNames().valueOf(attId).length() > 0;
          validAttributeIds.add(attId);
        }
        getAttributesStorage().checkSanity(attDataRecordId);
      }
    } finally {
      dataInputStream.close();
    }
  }
コード例 #2
0
ファイル: DeleteCustomer.java プロジェクト: Janendran/Java
  // Function use to load all Records from File when Application Execute.
  void populateArray() {

    try {
      fis = new FileInputStream("Bank.dat");
      dis = new DataInputStream(fis);
      // Loop to Populate the Array.
      while (true) {
        for (int i = 0; i < 6; i++) {
          records[rows][i] = dis.readUTF();
        }
        rows++;
      }
    } catch (Exception ex) {
      total = rows;
      if (total == 0) {
        JOptionPane.showMessageDialog(
            null,
            "Records File is Empty.\nEnter Records First to Display.",
            "BankSystem - EmptyFile",
            JOptionPane.PLAIN_MESSAGE);
        btnEnable();
      } else {
        try {
          dis.close();
          fis.close();
        } catch (Exception exp) {
        }
      }
    }
  }
コード例 #3
0
  public static Pair<String[], int[]> listAll(int parentId) {
    try {
      r.lock();
      try {
        final DataInputStream input = readAttribute(parentId, CHILDREN_ATT);
        if (input == null)
          return Pair.create(ArrayUtil.EMPTY_STRING_ARRAY, ArrayUtil.EMPTY_INT_ARRAY);

        final int count = DataInputOutputUtil.readINT(input);
        final int[] ids = ArrayUtil.newIntArray(count);
        final String[] names = ArrayUtil.newStringArray(count);
        for (int i = 0; i < count; i++) {
          int id = DataInputOutputUtil.readINT(input);
          id = id >= 0 ? id + parentId : -id;
          ids[i] = id;
          names[i] = getName(id);
        }
        input.close();
        return Pair.create(names, ids);
      } finally {
        r.unlock();
      }
    } catch (Throwable e) {
      throw DbConnection.handleError(e);
    }
  }
コード例 #4
0
ファイル: Graph.java プロジェクト: springer126/jDevelop
  private int Load_Nodes(DataInputStream inStream) {
    // need to open file and load data
    int node_id;
    int x_cor;
    int y_cor;
    // int n_nodes, n_edges, node_cnt, arrow_status;
    Node n;
    String line;
    String item1, item2, item3, item4;

    node_id = 0;
    x_cor = 0;
    y_cor = 0;
    // n_nodes = 0;
    // n_edges = 0;
    // arrow_status = -1;

    try {

      if ((line = inStream.readLine()) != null) {
        StringTokenizer Data = new StringTokenizer(line, " ");
        item1 = Data.nextToken();
        n_nodes = Integer.parseInt(item1);
        item2 = Data.nextToken();
        n_edges = Integer.parseInt(item2);
        item3 = Data.nextToken();
        arrow_status = Integer.parseInt(item3);
        // item4 = Data.nextToken();
        // type = Integer.parseInt( item4 );
        // graph = new GraphClass( n_nodes, n_edges, arrow_status );
        nodes = new Node[n_nodes];
        edges = new Edge[n_edges];

        // ???

        while ((this.Node_Cnt() < n_nodes) && ((line = inStream.readLine()) != null)) {
          Data = new StringTokenizer(line, " ");
          item1 = Data.nextToken();
          item2 = Data.nextToken();
          item3 = Data.nextToken();
          node_id = Integer.parseInt(item1);
          x_cor = Integer.parseInt(item2);
          y_cor = Integer.parseInt(item3);
          n = new Node(node_id, x_cor, y_cor);
          this.Add_Node(n);
        }
        if (n_nodes != 0) {
          source_node = nodes[0];
        }
      }
    } catch (IOException e) {
      System.err.println("error in file" + e.toString());
      System.exit(1);
    }
    return this.Node_Cnt();
  }
コード例 #5
0
  public static int findRootRecord(String rootUrl) throws IOException {
    try {
      w.lock();
      DbConnection.markDirty();
      final int root = getNames().enumerate(rootUrl);

      final DataInputStream input = readAttribute(1, CHILDREN_ATT);
      int[] names = ArrayUtil.EMPTY_INT_ARRAY;
      int[] ids = ArrayUtil.EMPTY_INT_ARRAY;

      if (input != null) {
        try {
          final int count = DataInputOutputUtil.readINT(input);
          names = ArrayUtil.newIntArray(count);
          ids = ArrayUtil.newIntArray(count);
          for (int i = 0; i < count; i++) {
            final int name = DataInputOutputUtil.readINT(input);
            final int id = DataInputOutputUtil.readINT(input);
            if (name == root) {
              return id;
            }

            names[i] = name;
            ids[i] = id;
          }
        } finally {
          input.close();
        }
      }

      final DataOutputStream output = writeAttribute(1, CHILDREN_ATT, false);
      int id;
      try {
        id = createRecord();
        DataInputOutputUtil.writeINT(output, names.length + 1);
        for (int i = 0; i < names.length; i++) {
          DataInputOutputUtil.writeINT(output, names[i]);
          DataInputOutputUtil.writeINT(output, ids[i]);
        }
        DataInputOutputUtil.writeINT(output, root);
        DataInputOutputUtil.writeINT(output, id);
      } finally {
        output.close();
      }

      return id;
    } finally {
      w.unlock();
    }
  }
コード例 #6
0
ファイル: FileManager2.java プロジェクト: OUHK/Java-Lab
  @Override
  public void actionPerformed(ActionEvent ev) {
    if (ev.getSource() == btn) {
      File file;
      String string = "";
      try {
        if (radioRead.isSelected()) {
          file = new File(txt.getText());
          DataInputStream input = new DataInputStream(new FileInputStream(file));
          int inByte;
          while ((inByte = input.read()) != -1) {
            string += (char) inByte;
          }
          input.close();

        } else if (radioEncrypt.isSelected()) {
          string = fileContent.getOut();
          String strEncrypt = new String();
          for (int i = 0; i < string.length(); i++) {
            char ch = string.charAt(i);
            if (ch >= 'A' && ch <= 'Z') {
              ch += 13;
              if (ch > 'Z') {
                ch -= 26;
              }
            } else if (ch >= 'a' && ch <= 'z') {
              ch += 13;
              if (ch > 'z') {
                ch -= 26;
              }
            }
            strEncrypt += ch;
          }
          string = strEncrypt;
        }

        if (fileContent == null) {
          fileContent = new FileContent(string);
        } else {
          fileContent.setVisible(true);
          fileContent.setOut(string);
        }

      } catch (FileNotFoundException e) {
        JOptionPane.showMessageDialog(this, "Can't find the file.");
      } catch (IOException e) {
        JOptionPane.showMessageDialog(this, "IO Exception " + e.getMessage());
      }
    }
  }
コード例 #7
0
ファイル: Graph.java プロジェクト: springer126/jDevelop
  private int Load_Edges(DataInputStream inStream, int num) {
    String line;
    String item1, item2, item3;
    int source_node;
    int dest_node;
    int value;
    int n_nodes, edge_cnt;
    // Node nodes_array[] = new Node[num]; // Wil
    Edge edge;
    n_nodes = num;
    Node nodes_array[];
    nodes_array = new Node[n_nodes];
    nodes_array = this.Node_Array(); // Wil
    edge_cnt = 0;

    try {
      while ((line = inStream.readLine()) != null) {
        StringTokenizer Data = new StringTokenizer(line, " ");
        item1 = Data.nextToken();
        item2 = Data.nextToken();
        item3 = Data.nextToken();
        source_node = Integer.parseInt(item1);
        dest_node = Integer.parseInt(item2);
        value = Integer.parseInt(item3);
        edge = new Edge(nodes_array[source_node - 1], nodes_array[dest_node - 1], value);
        this.Add_Edge(edge);
        edge_cnt++;
      }
      // inFile.close();
    } catch (IOException e) {
      System.err.println("Error in accessing URL: " + e.toString());
      System.exit(1);
    }
    return edge_cnt;
  }
コード例 #8
0
 public void run() {
   while (flag) {
     try {
       String msg = din.readUTF().trim();
       if (msg.startsWith("<#NICK_NAME#>")) {
         this.nick_name(msg);
       } else if (msg.startsWith("<#CLIENT_LEAVE#>")) {
         this.client_leave(msg);
       } else if (msg.startsWith("<#CHALLENGE#>")) {
         this.challenge(msg);
       } else if (msg.startsWith("<#AGREE#>")) {
         this.agree(msg);
       } else if (msg.startsWith("<#DISAGREE#>")) {
         this.disagree(msg);
       } else if (msg.startsWith("<#BUSY#>")) {
         this.busy(msg);
       } else if (msg.startsWith("<#MOVE#>")) {
         this.move(msg);
       } else if (msg.startsWith("<#SURRENDER#>")) {
         this.surrender(msg);
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
コード例 #9
0
    /**
     * Read State (color dots) from input stream
     *
     * @param instream
     * @throws IOException
     */
    public void readState(InputStream instream) throws IOException {
      DataInputStream in = new DataInputStream(new BufferedInputStream(instream));
      Map<Point, Color> new_state = new LinkedHashMap<Point, Color>();
      int num = in.readInt();
      for (int i = 0; i < num; i++) {
        Point point = new Point(in.readInt(), in.readInt());
        Color col = new Color(in.readInt());
        new_state.put(point, col);
      }

      synchronized (state) {
        state.clear();
        state.putAll(new_state);
        System.out.println("read " + state.size() + " elements");
        createOffscreenImage(true);
      }
    }
コード例 #10
0
  private static void deleteContentAndAttributes(int id) throws IOException {
    int content_page = getContentRecordId(id);
    if (content_page != 0) {
      getContentStorage().releaseRecord(content_page);
    }

    int att_page = getAttributeRecordId(id);
    if (att_page != 0) {
      final DataInputStream attStream = getAttributesStorage().readStream(att_page);
      while (attStream.available() > 0) {
        DataInputOutputUtil.readINT(attStream); // Attribute ID;
        int attAddress = DataInputOutputUtil.readINT(attStream);
        getAttributesStorage().deleteRecord(attAddress);
      }
      attStream.close();
      getAttributesStorage().deleteRecord(att_page);
    }
  }
コード例 #11
0
  private static int findAttributePage(int fileId, String attrId, boolean toWrite)
      throws IOException {
    checkFileIsValid(fileId);

    Storage storage = getAttributesStorage();

    int encodedAttrId = DbConnection.getAttributeId(attrId);
    int recordId = getAttributeRecordId(fileId);

    if (recordId == 0) {
      if (!toWrite) return 0;

      recordId = storage.createNewRecord();
      setAttributeRecordId(fileId, recordId);
    } else {
      DataInputStream attrRefs = storage.readStream(recordId);
      try {
        while (attrRefs.available() > 0) {
          final int attIdOnPage = DataInputOutputUtil.readINT(attrRefs);
          final int attrAddress = DataInputOutputUtil.readINT(attrRefs);

          if (attIdOnPage == encodedAttrId) return attrAddress;
        }
      } finally {
        attrRefs.close();
      }
    }

    if (toWrite) {
      Storage.AppenderStream appender = storage.appendStream(recordId);
      DataInputOutputUtil.writeINT(appender, encodedAttrId);
      int attrAddress = storage.createNewRecord();
      DataInputOutputUtil.writeINT(appender, attrAddress);
      DbConnection.REASONABLY_SMALL.myAttrPageRequested = true;
      try {
        appender.close();
      } finally {
        DbConnection.REASONABLY_SMALL.myAttrPageRequested = false;
      }
      return attrAddress;
    }

    return 0;
  }
コード例 #12
0
 // --------------------------------------------------
 public void close() {
   try {
     is.close();
     os.close();
     socket.close();
     responseArea.appendText("***Connection closed" + "\n");
   } catch (IOException e) {
     responseArea.appendText("IO Exception" + "\n");
   }
 }
コード例 #13
0
ファイル: InputData.java プロジェクト: GabrieleGe/OS
  public void readFile() throws IOException {
    try {

      FileInputStream fstream = new FileInputStream("dataIn.txt");
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));

      String strLine;
      int memi = -1;
      int strLineMemory = 59;

      while ((strLine = br.readLine()) != null) {

        t.data[strLineMemory++][1] = String.valueOf(strLine);
        memi++;

        size++;
        while ((strLine = br.readLine()) != null && !strLine.startsWith("*")) {

          String[] arr = strLine.split(" ");
          String command = arr[0];
          String operand = arr[1];

          toMemory(command, operand, memarray[memi]);
          memarray[memi] = memarray[memi] + 2;
          System.out.printf("%s %s ", command, operand);
        }
      }

      in.close();
    } catch (Exception e) { // Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }

    MOSMain mos = new MOSMain();
    mos.planner();

    t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    t.setSize(830, 800);
    t.setVisible(true);
    t.setTitle("Printer");
    sortTime();
  }
コード例 #14
0
 // --------------------------------------------------
 public void run() {
   String inputLine;
   try {
     while ((inputLine = is.readLine()) != null) {
       responseArea.appendText(inputLine + "\n");
     }
   } catch (IOException e) {
     responseArea.appendText("IO Exception" + "\n");
   }
 }
コード例 #15
0
ファイル: CipherChatClient.java プロジェクト: oghenez/mycila
 private void exchangeKeys() {
   try {
     output.write(modulus.toByteArray());
     byte[] buffer = new byte[ciphertextBlockSize];
     input.read(buffer);
     recipModulus = new BigInteger(1, buffer);
   } catch (IOException ioe) {
     System.err.println("Error establishing keys");
   }
 }
コード例 #16
0
  private final byte[] loadfile(String s, byte abyte0[]) {
    try {
      File file = new File(s);
      System.out.println("trying to load:" + file);
      int i = (int) file.length();
      DataInputStream datainputstream = new DataInputStream(new FileInputStream(s));
      byte abyte1[] = new byte[i];
      datainputstream.readFully(abyte1, 0, i);
      datainputstream.close();
      m.reset();
      m.update(abyte1);
      byte abyte2[] = m.digest();
      for (int j = 0; j < 20; j++) if (abyte2[j] != abyte0[j]) return null;

      return abyte1;
    } catch (Exception _ex) {
      return null;
    }
  }
コード例 #17
0
  // {{{ handleClient() method
  private boolean handleClient(final Socket client, DataInputStream in) throws Exception {
    int key = in.readInt();
    if (key != authKey) {
      Log.log(
          Log.ERROR,
          this,
          client + ": wrong" + " authorization key (got " + key + ", expected " + authKey + ")");
      in.close();
      client.close();

      return false;
    } else {
      // Reset the timeout
      client.setSoTimeout(0);

      Log.log(Log.DEBUG, this, client + ": authenticated" + " successfully");

      final String script = in.readUTF();
      Log.log(Log.DEBUG, this, script);

      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              try {
                NameSpace ns = new NameSpace(BeanShell.getNameSpace(), "EditServer namespace");
                ns.setVariable("socket", client);
                BeanShell.eval(null, ns, script);
              } catch (org.gjt.sp.jedit.bsh.UtilEvalError e) {
                Log.log(Log.ERROR, this, e);
              } finally {
                try {
                  BeanShell.getNameSpace().setVariable("socket", null);
                } catch (org.gjt.sp.jedit.bsh.UtilEvalError e) {
                  Log.log(Log.ERROR, this, e);
                }
              }
            }
          });

      return true;
    }
  } // }}}
コード例 #18
0
  public static void deleteRootRecord(int id) throws IOException {
    try {
      w.lock();
      DbConnection.markDirty();
      final DataInputStream input = readAttribute(1, CHILDREN_ATT);
      assert input != null;
      int count;
      int[] names;
      int[] ids;
      try {
        count = DataInputOutputUtil.readINT(input);

        names = ArrayUtil.newIntArray(count);
        ids = ArrayUtil.newIntArray(count);
        for (int i = 0; i < count; i++) {
          names[i] = DataInputOutputUtil.readINT(input);
          ids[i] = DataInputOutputUtil.readINT(input);
        }
      } finally {
        input.close();
      }

      final int index = ArrayUtil.find(ids, id);
      assert index >= 0;

      names = ArrayUtil.remove(names, index);
      ids = ArrayUtil.remove(ids, index);

      final DataOutputStream output = writeAttribute(1, CHILDREN_ATT, false);
      try {
        DataInputOutputUtil.writeINT(output, count - 1);
        for (int i = 0; i < names.length; i++) {
          DataInputOutputUtil.writeINT(output, names[i]);
          DataInputOutputUtil.writeINT(output, ids[i]);
        }
      } finally {
        output.close();
      }
    } finally {
      w.unlock();
    }
  }
コード例 #19
0
 private final int getuid(String s) {
   try {
     File file = new File(s + "uid.dat");
     if (!file.exists() || file.length() < 4L) {
       DataOutputStream dataoutputstream =
           new DataOutputStream(new FileOutputStream(s + "uid.dat"));
       dataoutputstream.writeInt((int) (Math.random() * 99999999D));
       dataoutputstream.close();
     }
   } catch (Exception _ex) {
   }
   try {
     DataInputStream datainputstream = new DataInputStream(new FileInputStream(s + "uid.dat"));
     int i = datainputstream.readInt();
     datainputstream.close();
     return i + 1;
   } catch (Exception _ex) {
     return 0;
   }
 }
コード例 #20
0
ファイル: CipherChatClient.java プロジェクト: oghenez/mycila
 // Close socket and IO streams, change appearance/functionality of some components
 private void closeAll() throws IOException {
   displayArea.append("\nConnection closing");
   output.close();
   input.close();
   connection.close();
   // We are no longer connected
   connection = null;
   // Change components
   serverField.setEditable(true);
   connectButton.setLabel("Connect to server above");
   enterField.setEnabled(false);
 }
コード例 #21
0
  public static int[] listRoots() throws IOException {
    try {
      r.lock();
      final DataInputStream input = readAttribute(1, CHILDREN_ATT);
      if (input == null) return ArrayUtil.EMPTY_INT_ARRAY;

      try {
        final int count = DataInputOutputUtil.readINT(input);
        int[] result = ArrayUtil.newIntArray(count);
        for (int i = 0; i < count; i++) {
          DataInputOutputUtil.readINT(input); // Name
          result[i] = DataInputOutputUtil.readINT(input); // Id
        }
        return result;
      } finally {
        input.close();
      }
    } finally {
      r.unlock();
    }
  }
コード例 #22
0
  public void run() {
    String objRouter = applet.getParameter("name");
    // No Internationalisation
    try {
      ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
      DataOutputStream outp = new DataOutputStream(byteStream);
      outp.writeInt(GenericConstants.ROUTER_PROPERTIES);
      outp.writeUTF(objRouter);
      outp.flush();

      byte[] bytes = byteStream.toByteArray();
      outp.close();
      byteStream.reset();
      byteStream.close();
      byte[] data = GenericSession.getInstance().syncSend(bytes);
      if (data != null) {
        DataInputStream inp = new DataInputStream(new ByteArrayInputStream(data));
        int reqId = inp.readInt();
        if (reqId == GenericConstants.ROUTER_PROPERTIES) {
          int length = inp.readInt();
          byte serverData[] = new byte[length];
          inp.readFully(serverData);
          routerobject = NmsClientUtil.deSerializeVector(serverData);
        }

        init();
        refresh();
        super.setVisible(true);
      }
      /*init();
      refresh();
      super.setVisible(true);*/

      else close();

    } catch (Exception e) {
      // NmsClientUtil.err(NmsClientUtil.getFrame(app),"IO Error sending request to server.
      // "+e);//No Internationalisation
    }
  }
コード例 #23
0
ファイル: ChatServer.java プロジェクト: cttiamin/JavaTest
    public void run() {
      try {

        DataInputStream dis = new DataInputStream(s.getInputStream());
        String str = dis.readUTF();
        while (str != null && str.length() != 0) {
          System.out.println(str);
          for (Iterator it = cClient.iterator(); it.hasNext(); ) {
            ClientConn cc = (ClientConn) it.next();
            if (this != cc) {
              cc.send(str);
            }
          }
          str = dis.readUTF();
          // send(str);
        }
        this.dispose();
      } catch (Exception e) {
        System.out.println("client quit");
        this.dispose();
      }
    }
コード例 #24
0
ファイル: Teste.java プロジェクト: mhadaniya/3cop005
  /**
   * Reads an image from an archived file and return it as ByteBuffer object.
   *
   * @author Mike Butler, Kiet Le
   */
  private ByteBuffer readImage(String filename, Dimension dim) {
    if (dim == null) dim = new Dimension(0, 0);
    ByteBuffer bytes = null;
    try {
      DataInputStream dis =
          new DataInputStream(getClass().getClassLoader().getResourceAsStream(filename));
      dim.width = dis.readInt();
      dim.height = dis.readInt();
      System.out.println("Creating buffer, width: " + dim.width + " height: " + dim.height);
      // byte[] buf = new byte[3 * dim.height * dim.width];
      bytes = BufferUtil.newByteBuffer(3 * dim.width * dim.height);
      for (int i = 0; i < bytes.capacity(); i++) {
        bytes.put(dis.readByte());
      }
      dis.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
    bytes.rewind();
    return bytes;
  }
コード例 #25
0
ファイル: Dmgcpu.java プロジェクト: Jorge-Martins/AVE
  private void loadData(DataInputStream sv, String directory) {
    try {
      int size = 0;
      // 8 bit registers
      registers[a] = sv.read();
      registers[b] = sv.read();
      registers[c] = sv.read();
      registers[d] = sv.read();
      registers[e] = sv.read();
      f = sv.read();

      // 16 bit registers
      sp = sv.readInt();
      pc = sv.readInt();
      hl = sv.readInt();

      gbcRamBank = sv.readInt();

      // write ram 8Kb
      size = mainRam.length;
      if (sv.read(mainRam) != size) {
        System.out.println("Dmgcpu.loadState.loadData: mainRam loaded has different size!");
        System.exit(-1);
      }

      // write oam (used mainly for registers) 256 bytes
      size = oam.length;
      if (sv.read(oam) != size) {
        System.out.println("Dmgcpu.loadState.loadData: oam loaded has different size!");
        System.exit(-1);
      }

      saveInterrupt = false;
      loadStateInterrupt = false;
      saveCheckpointInterrupt = false;
      loadCheckpointInterrupt = false;

    } catch (IOException e) {
      System.out.println("Dmgcpu.saveState.loadData: Could not read file " + directory);
      System.out.println("Error Message: " + e.getMessage());
      System.exit(-1);
    }
  }
コード例 #26
0
  public static int[] list(int id) {
    try {
      r.lock();
      try {
        final DataInputStream input = readAttribute(id, CHILDREN_ATT);
        if (input == null) return ArrayUtil.EMPTY_INT_ARRAY;

        final int count = DataInputOutputUtil.readINT(input);
        final int[] result = ArrayUtil.newIntArray(count);
        for (int i = 0; i < count; i++) {
          int childId = DataInputOutputUtil.readINT(input);
          childId = childId >= 0 ? childId + id : -childId;
          result[i] = childId;
        }
        input.close();
        return result;
      } finally {
        r.unlock();
      }
    } catch (Throwable e) {
      throw DbConnection.handleError(e);
    }
  }
コード例 #27
0
  /** Implement the run() method for the thread */
  public void run() {
    try {
      // Create data input and output streams
      DataInputStream fromPlayer1 = new DataInputStream(player1.getInputStream());
      DataOutputStream toPlayer1 = new DataOutputStream(player1.getOutputStream());
      DataInputStream fromPlayer2 = new DataInputStream(player2.getInputStream());
      DataOutputStream toPlayer2 = new DataOutputStream(player2.getOutputStream());

      // Write anything to notify player 1 to start
      // This is just to let player 1 know to start
      toPlayer1.writeInt(1);

      // Continuously serve the players and determine and report
      // the game status to the players
      while (true) {
        // Receive a move from player 1
        int row = fromPlayer1.readInt();
        int column = fromPlayer1.readInt();
        int yCoordinate = game.insert("[X]", column);

        // Check if Player 1 wins
        if (game.isWinner(column, yCoordinate, "[X]")) { // if a  winner is found
          toPlayer1.writeInt(PLAYER1_WON);
          toPlayer2.writeInt(PLAYER1_WON);
          sendMove(toPlayer2, row, column);
          break; // Break the loop
        } else {
          toPlayer2.writeInt(CONTINUE);
          sendMove(toPlayer2, row, column);
        }
        // Receive a move from Player 2
        row = fromPlayer2.readInt();
        column = fromPlayer2.readInt();
        yCoordinate = game.insert("[O]", column);
        // Check if Player 2 wins
        if (game.isWinner(column, yCoordinate, "[O]")) { // if a  winner is found
          toPlayer1.writeInt(PLAYER2_WON);
          toPlayer2.writeInt(PLAYER2_WON);
          sendMove(toPlayer1, row, column);
          break; // Break the loop
        } else if (game.boardIsFull()) { // Check if all cells are filled
          toPlayer1.writeInt(DRAW);
          toPlayer2.writeInt(DRAW);
          sendMove(toPlayer1, row, column);
          break;
        } else {
          // Notify player 2 to take the turn
          toPlayer1.writeInt(CONTINUE);
          // Send player 1's selected row and column to player 2
          sendMove(toPlayer1, row, column);
        }
      }
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
コード例 #28
0
ファイル: Dmgcpu.java プロジェクト: Jorge-Martins/AVE
  public void loadState(String extension) {
    String directory = cartridge.romFileName + extension;

    try {
      reset();

      FileInputStream fl = new FileInputStream(directory);
      DataInputStream sv = new DataInputStream(fl);

      // write cpu data
      loadData(sv, directory);

      // write battery ram
      cartridge.loadData(sv, directory);

      // write graphic memory
      graphicsChip.loadData(sv, directory);

      // writes io state
      ioHandler.loadData(sv, directory);

      sv.close();
      fl.close();

    } catch (FileNotFoundException ex) {
      System.out.println("Dmgcpu.loadState: Could not open file " + directory);
      System.out.println("Error Message: " + ex.getMessage());
      System.exit(-1);
    } catch (IOException ex) {
      System.out.println("Dmgcpu.loadState: Could not read file " + directory);
      System.out.println("Error Message: " + ex.getMessage());
      System.exit(-1);
    }

    System.out.println("Loaded stage!");
  }
コード例 #29
0
  public void nick_name(String msg) {
    try {
      String name = msg.substring(13);
      this.setName(name);
      Vector v = father.onlineList;
      boolean isRepeatedName = false;
      int size = v.size();
      for (int i = 0; i < size; i++) {
        ServerAgentThread tempSat = (ServerAgentThread) v.get(i);
        if (tempSat.getName().equals(name)) {
          isRepeatedName = true;
          break;
        }
      }
      if (isRepeatedName == true) {
        dout.writeUTF("<#NAME_REPEATED#>");
        din.close();
        dout.close();
        sc.close();
        flag = false;
      } else {
        v.add(this);
        father.refreshList();
        String nickListMsg = "";
        StringBuilder nickListMsgSb = new StringBuilder();
        size = v.size();
        for (int i = 0; i < size; i++) {
          ServerAgentThread tempSat = (ServerAgentThread) v.get(i);
          nickListMsgSb.append("!");
          nickListMsgSb.append(tempSat.getName());
        }
        nickListMsgSb.append("<#NICK_LIST#>");
        nickListMsg = nickListMsgSb.toString();
        Vector tempv = father.onlineList;
        size = tempv.size();
        for (int i = 0; i < size; i++) {
          ServerAgentThread tempSat = (ServerAgentThread) tempv.get(i);
          tempSat.dout.writeUTF(nickListMsg);
          if (tempSat != this) {
            tempSat.dout.writeUTF("<#MSG#>" + this.getName() + "is now online....");
          }
        }
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #30
0
ファイル: CipherChatClient.java プロジェクト: oghenez/mycila
 private void go() {
   try {
     // Read as long as there is input
     byte[] buffer = new byte[ciphertextBlockSize];
     boolean disconnectMsgSent = false;
     while (connection != null && !disconnectMsgSent && input.read(buffer) != -1) {
       // Decipher the bytes read in
       byte[] plaintext = Ciphers.RSADecipherWSalt(buffer, decipherExp, modulus);
       if (plaintext.length == 1 && plaintext[0] == 0) {
         disconnectMsgSent = true;
         closeAll();
       } else {
         // convert to a string and display
         message = new String(plaintext);
         displayArea.append("\n" + message);
       }
     }
   } catch (IOException ioe) {
     // Server disconnected-we can reconnect if we wish
   }
 }