Example #1
0
  // Function use to Save Records to File After Deleting the Record of User Choice.
  void deleteFile() {

    try {
      FileOutputStream fos = new FileOutputStream("Bank.dat");
      DataOutputStream dos = new DataOutputStream(fos);
      if (records != null) {
        for (int i = 0; i < total; i++) {
          for (int r = 0; r < 6; r++) {
            dos.writeUTF(records[i][r]);
            if (records[i][r] == null) break;
          }
        }
        JOptionPane.showMessageDialog(
            this,
            "Record has been Deleted Successfuly.",
            "BankSystem - Record Deleted",
            JOptionPane.PLAIN_MESSAGE);
        txtClear();
      } else {
      }
      dos.close();
      fos.close();
    } catch (IOException ioe) {
      JOptionPane.showMessageDialog(
          this,
          "There are Some Problem with File",
          "BankSystem - Problem",
          JOptionPane.PLAIN_MESSAGE);
    }
  }
Example #2
0
  public void saveState(String extension) {
    String directory = (cartridge.romFileName + extension);

    try {
      FileOutputStream fl = new FileOutputStream(directory);
      DataOutputStream sv = new DataOutputStream(fl);

      saveData(sv, directory);

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

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

      // write io state
      ioHandler.saveData(sv, directory);

      // stats.printStats();

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

    } catch (FileNotFoundException e) {
      System.out.println("Dmgcpu.saveState: Could not open file " + directory);
      System.out.println("Error Message: " + e.getMessage());
      System.exit(-1);
    } catch (IOException e) {
      System.out.println("Dmgcpu.saveState: Could not write to file " + directory);
      System.out.println("Error Message: " + e.getMessage());
      System.exit(-1);
    }

    System.out.println("Saved stage!");
  }
Example #3
0
 public void addScore() {
   try {
     out88.writeUTF("加分");
     out88.flush();
     out88.writeUTF("");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Example #4
0
 public void cutScore(String whom) {
   try {
     out88.writeUTF("减分");
     out88.flush();
     out88.writeUTF("");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Example #5
0
  private void saveData(DataOutputStream sv, String directory) {
    try {
      // 8 bit registers
      sv.write(registers[a]);
      sv.write(registers[b]);
      sv.write(registers[c]);
      sv.write(registers[d]);
      sv.write(registers[e]);
      sv.write(f);

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

      sv.writeInt(gbcRamBank);

      // write ram 8Kb
      sv.write(mainRam);

      // write oam (used mainly for registers) 256 bytes
      sv.write(oam);

    } catch (IOException e) {
      System.out.println("Dmgcpu.saveState.saveData: Could not write to file " + directory);
      System.out.println("Error Message: " + e.getMessage());
      System.exit(-1);
    }
  }
  public void guardarVentaIngreso() {
    try {
      FileOutputStream fos = new FileOutputStream("ingreso.dat");
      DataOutputStream dos = new DataOutputStream(fos);
      dos.writeDouble(sistema.getEmpresa().getIngreso());
      dos.writeInt(sistema.getEmpresa().getNumVentas());
      dos.close();
    } catch (IOException ex) {

    }
  }
Example #7
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();
    }
  }
Example #8
0
 public void disconnect() {
   try {
     dos.close();
     s.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 /**
  * \ Draw saved State (color dots on panel) on WhiteBoard
  *
  * @param outstream
  * @throws IOException
  */
 public void writeState(OutputStream outstream) throws IOException {
   if (state == null) return;
   synchronized (state) {
     DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(outstream));
     // DataOutputStream dos=new DataOutputStream(outstream);
     dos.writeInt(state.size());
     for (Map.Entry<Point, Color> entry : state.entrySet()) {
       Point point = entry.getKey();
       Color col = entry.getValue();
       dos.writeInt(point.x);
       dos.writeInt(point.x);
       dos.writeInt(col.getRGB());
     }
     dos.flush();
     System.out.println("wrote " + state.size() + " elements");
   }
 }
Example #10
0
 public void disconnect() {
   try {
     dos.close();
     s.close();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Example #11
0
 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");
   }
 }
 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;
   }
 }
Example #13
0
 // 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);
 }
Example #14
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
    }
  }
Example #15
0
 /**
  * Bring up a file chooser allowing the user to choose a location to save the unchanged contents
  * of the text area as a text file. Saves it to this file. Displays an error message if a problem
  * occurs or if the file already exists.
  */
 private void saveText() {
   if (save_chooser == null) save_chooser = new JFileChooser();
   int browse_return = save_chooser.showSaveDialog(this);
   if (browse_return == JFileChooser.APPROVE_OPTION) {
     String selected_path = save_chooser.getSelectedFile().getAbsolutePath();
     File selected_file =
         mckay.utilities.staticlibraries.FileMethods.getNewFileForWriting(selected_path, false);
     if (selected_file != null) {
       try {
         System.out.println("a");
         DataOutputStream writer =
             mckay.utilities.staticlibraries.FileMethods.getDataOutputStream(selected_file);
         System.out.println("b");
         writer.writeBytes(getText());
         System.out.println("c");
       } catch (Exception e) {
         JOptionPane.showMessageDialog(
             null, "Unable to write file.", "ERROR", JOptionPane.ERROR_MESSAGE);
       }
     }
   }
 }
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == jbSaveLayer) {
      try {
        FileOutputStream fout = new FileOutputStream(jtfCengMing.getText() + ".wyf");
        ObjectOutputStream oout = new ObjectOutputStream(fout);
        oout.writeObject(itemArray);
        oout.close();
        fout.close();
      } catch (Exception ea) {
        ea.printStackTrace();
      }
    } else if (e.getSource() == jbLoadLayer) {
      try {
        FileInputStream fin = new FileInputStream(jtfCengMing.getText() + ".wyf");
        ObjectInputStream oin = new ObjectInputStream(fin);
        itemArray = (Item[][]) oin.readObject();

        oin.close();
        fin.close();
        this.flush();
      } catch (Exception ea) {
        ea.printStackTrace();
      }
      lvp.repaint();
    } else if (e.getSource() == jbLoadAll) { // 全部铺上当前选中

      for (int row = 0; row < 40; row++) {
        for (int col = 0; col < 60; col++) {
          Item item = ((Item) (jl.getSelectedValue())).clone();
          itemArray[row][col] = item;
          if (item != null) {
            item.setPosition(col, row);
          }
        }
      }

      lvp.repaint();
    } else if (e.getSource() == jbCreate) { // 生成源代码

      try {
        FileOutputStream fout = null;
        DataOutputStream dout = null;
        fout = new FileOutputStream("maps.so");
        dout = new DataOutputStream(fout);
        int totalBlocks = 0;

        for (int i = 0; i < 40; i++) {
          for (int j = 0; j < 60; j++) {
            Item item = itemArray[i][j];
            if (item != null) {
              totalBlocks++;
            }
          }
        }
        System.out.println("totalBlocks=" + totalBlocks);

        // 写入不空块的数量
        dout.writeInt(totalBlocks);

        for (int i = 0; i < 40; i++) {
          for (int j = 0; j < 60; j++) {
            Item item = itemArray[i][j];
            if (item != null) {
              int w = item.w; // 元素的图片宽度
              int h = item.h; // 元素的图片高度
              int col = item.col; // 元素的地图列
              int row = item.row; // 元素的地图行
              int pCol = item.pCol; // 元素的占位列
              int pRow = item.pRow; // 元素的占位行
              String leiMing = item.leiMing; // 类名

              int[][] notIn = item.notIn; // 不可通过
              int[][] keYu = item.keYu; // 可遇矩阵

              // 计算图片下标
              int outBitmapInxex = 0;
              if (leiMing.equals("Grass")) {
                outBitmapInxex = 0;
              } else if (leiMing.equals("XiaoHua1")) {
                outBitmapInxex = 1;
              } else if (leiMing.equals("MuZhuang")) {
                outBitmapInxex = 2;
              } else if (leiMing.equals("XiaoHua2")) {
                outBitmapInxex = 3;
              } else if (leiMing.equals("Road")) {
                outBitmapInxex = 4;
              } else if (leiMing.equals("Jing")) {
                outBitmapInxex = 5;
              }

              dout.writeByte(outBitmapInxex); // 记录图片下标
              dout.writeByte(0); // 记录可遇标志 0-不可遇 底层都不可遇
              dout.writeByte(w); // 图片宽度
              dout.writeByte(h); // 图片高度
              dout.writeByte(col); // 总列数
              dout.writeByte(row); // 总行数
              dout.writeByte(pCol); // 占位列
              dout.writeByte(pRow); // 占位行

              int bktgCount = notIn.length; // 不可通过点的数量
              dout.writeByte(bktgCount); // 写入不可通过点的数量

              for (int k = 0; k < bktgCount; k++) {
                dout.writeByte(notIn[k][0]);
                dout.writeByte(notIn[k][1]);
              }
            }
          }
        }

        dout.close();
        fout.close();

      } catch (Exception ea) {
        ea.printStackTrace();
      }
    }
  }
Example #17
0
  /** Submits POST command to the server, and reads the reply. */
  public boolean post(
      String url,
      String fileName,
      String cryptToken,
      String type,
      String path,
      String content,
      String comment)
      throws IOException {

    String sep = "89692781418184";
    while (content.indexOf(sep) != -1) sep += "x";

    String message = makeMimeForm(fileName, cryptToken, type, path, content, comment, sep);

    // for test
    // URL server = new URL("http", "localhost", 80, savePath);
    URL server =
        new URL(getCodeBase().getProtocol(), getCodeBase().getHost(), getCodeBase().getPort(), url);
    URLConnection connection = server.openConnection();

    connection.setAllowUserInteraction(false);
    connection.setDoOutput(true);
    // connection.setDoInput(true);
    connection.setUseCaches(false);

    connection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + sep);
    connection.setRequestProperty("Content-length", Integer.toString(message.length()));

    // System.out.println(url);
    String replyString = null;
    try {
      DataOutputStream out = new DataOutputStream(connection.getOutputStream());
      out.writeBytes(message);
      out.close();
      // System.out.println("Wrote " + message.length() +
      //		   " bytes to\n" + connection);

      try {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String reply = null;
        while ((reply = in.readLine()) != null) {
          if (reply.startsWith("ERROR ")) {
            replyString = reply.substring("ERROR ".length());
          }
        }
        in.close();
      } catch (IOException ioe) {
        replyString = ioe.toString();
      }
    } catch (UnknownServiceException use) {
      replyString = use.getMessage();
      System.out.println(message);
    }
    if (replyString != null) {
      // System.out.println("---- Reply " + replyString);
      if (replyString.startsWith("URL ")) {
        URL eurl = getURL(replyString.substring("URL ".length()));
        getAppletContext().showDocument(eurl);
      } else if (replyString.startsWith("java.io.FileNotFoundException")) {
        // debug; when run from appletviewer, the http connection
        // is not available so write the file content
        if (path.endsWith(".draw") || path.endsWith(".map")) System.out.println(content);
      } else showStatus(replyString);
      return false;
    } else {
      showStatus(url + " saved");
      return true;
    }
  }
Example #18
0
  public void actionPerformed(ActionEvent e) {
    Object source = e.getSource();
    // Client pressed enter in the message entry field-send it
    if (source == enterField) {
      // Get the message
      message = e.getActionCommand();
      try {
        // Encipher the message
        if (message.length() > plaintextBlockSize)
          message = message.substring(0, plaintextBlockSize);
        byte[] ciphertext =
            Ciphers.RSAEncipherWSalt(message.getBytes(), BigIntegerMath.THREE, recipModulus, sr);
        // Send to the server
        output.write(ciphertext);
        output.flush();
        // Display same message in client output area
        displayArea.append("\n" + message);
        enterField.setText("");
      } catch (IOException ioe) {
        displayArea.append("\nError writing message");
      }
    } else if (source == connectButton) {
      if (connection != null) { // Already connected-button press now means disconnect
        try {
          // Send final message of 0
          byte[] lastMsg = new byte[1];
          lastMsg[0] = 0;
          output.write(Ciphers.RSAEncipherWSalt(lastMsg, BigIntegerMath.THREE, recipModulus, sr));
          output.flush();
          // close connection and IO streams, change some components
          closeAll();
        } catch (IOException ioe) {
          displayArea.append("\nError closing connection");
        }
      } else { // Not connected-connect
        // Get name of server to connect to
        chatServer = serverField.getText();
        displayArea.setText("Attempting connection to " + chatServer);
        try {
          // Set up the socket
          connection = new Socket(chatServer, 55555);

          displayArea.append("\nConnected to: " + connection.getInetAddress().getHostName());

          // Set up the IO streams
          output = new DataOutputStream(connection.getOutputStream());
          output.flush();
          input = new DataInputStream(connection.getInputStream());

          // Exchange public keys with the server-send yours, get theirs
          exchangeKeys();

          // Change appearance/functionality of some components
          serverField.setEditable(false);
          connectButton.setLabel("Disconnect from server above");
          enterField.setEnabled(true);
          // Set up a thread to listen for the connection
          listener =
              new Thread(
                  new Runnable() {
                    public void run() {
                      go();
                    }
                  });
          listener.start();
        } catch (IOException ioe) {
          displayArea.append("\nError connecting to " + chatServer);
        }
      }
    }
  }
Example #19
0
    public void
        run() { // ************************************************************************************

      String jsonText2 = new String("");

      JSONObject obj_out = new JSONObject();

      ServerSocket welcomeSocket;

      while (true) {

        try { // *********************************************************

          welcomeSocket = new ServerSocket(network.api_port, 0, InetAddress.getByName("localhost"));
          Socket connectionSocket = welcomeSocket.accept();
          BufferedReader inFromClient =
              new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
          DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
          clientSentence = inFromClient.readLine();

          JSONParser parser = new JSONParser();

          try { // *********************************************************

            statex = "0";
            responsex = "e00";
            jsonText = "";

            if (!clientSentence.contains("")) {
              throw new EmptyStackException();
            }
            Object obj = parser.parse(clientSentence);

            jsonObject = (JSONObject) obj;

            String request = (String) jsonObject.get("request");

            String item_id = new String("");
            String item_array = new String("");
            String old_key = new String("");
            String node = new String("");
            try {
              item_id = (String) jsonObject.get("item_id").toString();
            } catch (Exception e) {
              System.out.println("extra info no item_id...");
            }
            try {
              item_array = (String) jsonObject.get("item_array").toString();
            } catch (Exception e) {
              System.out.println("extra info no item_array...");
            }
            try {
              old_key = (String) jsonObject.get("key").toString();
            } catch (Exception e) {
              System.out.println("extra info no key...");
            }
            try {
              node = (String) jsonObject.get("node").toString();
            } catch (Exception e) {
              System.out.println("extra info no node...");
            }

            while (network.database_in_use == 1 && !request.equals("status")) {

              System.out.println("Database in use...");
              try {
                Thread.sleep(1000);
              } catch (InterruptedException e) {
              }
            } // **************************************************************

            if (request.equals("status")) {
              statex = "1";
              responsex = get_status();
            } // ***************************
            else if (request.equals("get_version")) {
              statex = "1";
              responsex = network.versionx;
            } //
            else if (request.equals("get_tor_active")) {
              statex = "1";
              responsex = Integer.toString(network.tor_active);
            } //
            else if (request.equals("get_last_block")) {
              statex = "1";
              responsex = network.last_block_id;
            } //
            else if (request.equals("get_last_block_timestamp")) {
              statex = "1";
              responsex = network.last_block_timestamp;
            } //
            else if (request.equals("get_last_block_hash")) {
              statex = "1";
              responsex = network.last_block_idx;
            } //
            else if (request.equals("get_difficulty")) {
              statex = "1";
              responsex = Long.toString(network.difficultyx);
            } //
            else if (request.equals("get_last_mining_id")) {
              statex = "1";
              responsex = network.last_block_mining_idx;
            } //
            else if (request.equals("get_prev_mining_id")) {
              statex = "1";
              responsex = network.prev_block_mining_idx;
            } //
            else if (request.equals("get_last_unconfirmed_id")) {
              statex = "1";
              responsex = get_item_ids();
            } //
            else if (request.equals("get_my_token_total")) {
              statex = "1";
              responsex = Integer.toString(network.database_listings_owner);
            } //
            else if (request.equals("get_my_id_list")) {
              statex = "1";
              responsex = get_item_ids();
            } //
            else if (request.equals("get_my_ids_limit")) {
              statex = "1";
              responsex = get_item_ids();
            } //
            else if (request.equals("get_token")) {
              statex = "1";
              responsex = get_item_array(item_id);
            } //
            else if (request.equals("get_settings")) {
              statex = "1";
              responsex = get_settings_array();
            } //
            else if (request.equals("get_mining_info")) {
              statex = "1";
              responsex = get_item_array(item_id);
            } //
            else if (request.equals("get_new_keys")) {
              statex = "1";
              responsex = build_keysx();
            } //
            else if (request.equals("delete_node")) {
              statex = "1";
              responsex = delete_node(node);
            } //
            else if (request.equals("delete_all_nodes")) {
              statex = "1";
              responsex = delete_all_nodes();
            } //
            else if (request.equals("set_new_node")) {
              statex = "1";
              responsex = set_new_node(node);
            } //
            else if (request.equals("set_old_key")) {
              statex = "1";
              responsex = set_old_key(old_key);
            } //
            else if (request.equals("set_new_block")) {
              statex = "1";
              responsex = set_new_block(item_array);
            } //
            else if (request.equals("set_edit_block")) {
              statex = "1";
              update_state = "set_edit_block";
              responsex = update_token(item_array);
            } //
            else if (request.equals("set_transfer_block")) {
              statex = "1";
              update_state = "set_transfer_block";
              responsex = update_token(item_array);
            } //
            else if (request.equals("system_restart")) {
              statex = "1";
              responsex = "restarting";
              toolkit = Toolkit.getDefaultToolkit();
              xtimerx = new Timer();
              xtimerx.schedule(new RemindTask_restart(), 0);
            } //
            else if (request.equals("system_exit")) {
              statex = "1";
              System.exit(0);
            } //
            else {
              statex = "0";
              responsex = "e01 UnknownRequestException";
            }

          } // try
          catch (ParseException e) {
            e.printStackTrace();
            statex = "0";
            responsex = "e02 ParseException";
          } catch (Exception e) {
            e.printStackTrace();
            statex = "0";
            responsex = "e03 Exception";
          }

          JSONObject obj = new JSONObject();
          obj.put("response", statex);
          try {
            obj.put("message", responsex);
          } catch (Exception e) {
            e.printStackTrace();
          }

          StringWriter outs = new StringWriter();
          obj.writeJSONString(outs);
          jsonText = outs.toString();
          System.out.println("SEND RESPONSE " + responsex);

          outToClient.writeBytes(jsonText + '\n');
          welcomeSocket.close();

        } catch (Exception e) {
          e.printStackTrace();
          System.out.println("Server ERROR x3");
        }
      } // **********while
    } // runx***************************************************************************************************
Example #20
0
 /** Send the move to other player */
 private void sendMove(DataOutputStream out, int row, int column) throws IOException {
   out.writeInt(row); // Send row index
   out.writeInt(column); // Send column index
 }
Example #21
0
 // =========================================================
 public void send(String strToSend) throws IOException // SEND METHOD
     {
   dos.writeBytes(strToSend + '\n');
   System.out.println("SENT>>>> " + id + ": " + strToSend);
 }
Example #22
0
    @Override
    public void run() {

      try {
        // Create data input and output streams
        DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
        DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());

        // Set up a byte buffer to capture the file from the client
        byte[] buffer = new byte[BUFFER_SIZE];
        OutputStream outputStream = null;
        String fileName = "";
        boolean createFile = true;
        int bytesReceived = 0;
        long totalBytesReceived = 0;
        long fileSize = 0;

        // Continuously serve the client
        while (true) {
          bytesReceived = inputFromClient.read(buffer);

          if (bytesReceived
              > 0) { // Get the file transmission header from the initial client packet
            String transmitHeader = new String(buffer, 0, bytesReceived);
            // transmitHeader = transmitHeader.substring(0, bytesReceived).trim().;
            String[] header = transmitHeader.split(HEADER_DEL);
            fileSize = Long.parseLong(header[0]);
            fileName = header[1];

            // Send receipt acknowledgment back to the client. Just send back the number of bytes
            // received.
            outputToClient.writeInt(bytesReceived);

            // Reinitialize buffer values
            buffer = new byte[BUFFER_SIZE];
            bytesReceived = 0;
          }

          // Wait for client to send bytes
          while ((bytesReceived = inputFromClient.read(buffer)) != -1) {
            if (inputFromClient.available() > 0) {
              if (createFile) { // Get a unique name for the file to be received
                fileName = textFolder.getText() + fileName; // getUniqueFileName();
                outputStream = createFile(fileName);
                createFile = false;
                textArea.append("Receiving file from client.\n");
              }

              // Write bytes to file
              outputStream.write(buffer, 0, bytesReceived);
            } else { // We get here if no more data is available, but some bytes were already
              // received

              // If bytes were received and the file wasn't already created,
              // it means that the file was smaller than our buffer size.
              // Create the file...
              if (bytesReceived > 0
                  && createFile) { // Get a unique name for the file to be received
                fileName = textFolder.getText() + fileName; // getUniqueFileName();
                outputStream = createFile(fileName);
                createFile = false;
                textArea.append("Receiving file from client.\n");
              }

              if (outputStream != null) {
                if (bytesReceived > 0) { // Write remaining bytes to file, if any
                  outputStream.write(buffer, 0, bytesReceived);
                }

                outputStream.flush();
                outputStream.close();
                textArea.append("Received file successfully. Saved as " + fileName + "\n");

                // Return success to client.
                outputToClient.writeInt(0);
              }

              // Reset creation flag
              createFile = true;
              break;
            }

            // Reinitialize buffer values
            buffer = new byte[BUFFER_SIZE];
            bytesReceived = 0;
          }
        }
      } catch (IOException e) {
        System.err.println(e);
      }
    }
Example #23
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);
    }
  }
Example #24
0
 /* (non-Javadoc)
  * @see edu.mit.csail.cgs.utils.Saveable#save(java.io.DataOutputStream)
  */
 public void save(DataOutputStream dos) throws IOException {
   dos.writeInt(2);
   super.save(dos);
 }
Example #25
0
 public void send(String str) throws IOException {
   DataOutputStream dos = new DataOutputStream(s.getOutputStream());
   dos.writeUTF(str);
 }