コード例 #1
1
  @Override
  public void run() {
    try {
      // Open socket
      socket = new Socket("127.0.0.1", 5432);
      // Get input streams
      DataOutputStream writer =
          new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
      DataInputStream scanner = new DataInputStream(socket.getInputStream());
      // Send calculation data
      writer.writeDouble(zoom);
      writer.writeDouble(zoomTranslateX);
      writer.writeDouble(zoomTranslateY);
      writer.writeInt(level);
      writer.writeInt(mode);
      writer.flush();
      System.out.println("Sent data");

      // Wait for server to do calculations
      while (scanner.available() == 0) {
        Thread.sleep(level);
      }
      System.out.println("Start drawing");
      // Start reading and drawing
      application.clearKochPanel();
      int counter = 0;
      while (true) {
        if (scanner.available() > 0) {
          application.drawEdge(
              new Edge(
                  scanner.readDouble(),
                  scanner.readDouble(),
                  scanner.readDouble(),
                  scanner.readDouble(),
                  Color.hsb(scanner.readDouble(), 1, 1)));
          counter = 0;
        } else {
          Thread.sleep(10);
          counter++;
          if (counter > 10) {
            break;
          }
        }
      }
      System.out.println("Finished drawing!");

      writer.writeChar('H');
      writer.flush();
      writer.close();
      scanner.close();
      socket.close();
    } catch (Exception e) {
      System.out.println("Receiving edges failed!");
      System.out.println(e.getMessage());
      Thread.currentThread().interrupt();
    }
  }
コード例 #2
0
ファイル: Packet2Login.java プロジェクト: SuperCram/supercram
 @Override
 void write(DataOutputStream dos) throws IOException {
   super.write(dos);
   dos.writeInt(MyVersion);
   dos.writeInt(ProtocolVersion);
   dos.writeInt(username.length());
   for (int i = 0; i < username.length(); i++) dos.writeChar(username.charAt(i));
   dos.writeInt(password.length());
   for (int i = 0; i < password.length(); i++) dos.writeChar(password.charAt(i));
 }
コード例 #3
0
 @Override
 public void write(DataOutputStream buf) throws IOException, NotSupportedOperationException {
   buf.writeByte(protocol);
   buf.writeShort(username.length());
   for (int i = 0; i < username.length(); ++i) {
     buf.writeChar(username.charAt(i));
   }
   buf.writeShort(host.length());
   for (int i = 0; i < host.length(); ++i) {
     buf.writeChar(host.charAt(i));
   }
   buf.writeInt(port);
 }
コード例 #4
0
 public void saveToFile(String filename) throws IOException {
   DataOutputStream dos = new DataOutputStream(new FileOutputStream(filename));
   dos.writeInt(integer);
   dos.writeDouble(decimal);
   dos.writeChar(character);
   dos.close();
 }
コード例 #5
0
  public static void main(String args[]) {
    OutputStream f = null;
    try {
      f = new FileOutputStream(args[0]);
    } catch (IOException e) {
      System.out.println("Apertura fallita");
      e.printStackTrace();
      // System.exit(1);
    }

    String a = "grgregre";

    DataOutputStream df = new DataOutputStream(f);

    float f1 = 5.1415F;
    char c1 = 'X';
    boolean b1 = true;
    double d1 = 1.4141;
    try {

      df.writeFloat(f1);
      df.writeBoolean(b1);
      df.writeDouble(d1);
      df.writeChar(c1);
      df.writeInt(11);
      df.close();
    } catch (IOException e) {
      e.printStackTrace();
      System.out.println("Scrittura fallita");

      // System.exit(1);
    }
  }
コード例 #6
0
 /**
  * Writes this <code>State</code> to the given output stream.
  *
  * @param dos the data output stream
  * @throws IOException if an error occurs
  */
 public void writeBinary(DataOutputStream dos) throws IOException {
   dos.writeInt(TYPE);
   dos.writeInt(index);
   dos.writeChar(c);
   dos.writeInt(qtrue);
   dos.writeInt(qfalse);
 }
コード例 #7
0
  public static void main(String[] args) throws IOException {
    // Create a FileOutputStream.
    FileOutputStream outputFile = new FileOutputStream("primitives.data");

    // Create a DataOutputStream which is chained to the FileOutputStream.
    DataOutputStream outputStream = new DataOutputStream(outputFile);

    // Write Java primitive values in binary representation:
    outputStream.writeBoolean(true);
    outputStream.writeChar('A'); // int written as Unicode char
    outputStream.writeByte(Byte.MAX_VALUE); // int written as 8-bits byte
    outputStream.writeShort(Short.MIN_VALUE); // int written as 16-bits short
    outputStream.writeInt(Integer.MAX_VALUE);
    outputStream.writeLong(Long.MIN_VALUE);
    outputStream.writeFloat(Float.MAX_VALUE);
    outputStream.writeDouble(Math.PI);

    // Close the output stream, which also closes the underlying stream.
    outputStream.flush();
    outputStream.close();

    // Create a FileInputStream.
    FileInputStream inputFile = new FileInputStream("primitives.data");

    // Create a DataInputStream which is chained to the FileInputStream.
    DataInputStream inputStream = new DataInputStream(inputFile);

    // Read the binary representation of Java primitive values
    // in the same order they were written out:
    boolean v = inputStream.readBoolean();
    char c = inputStream.readChar();
    byte b = inputStream.readByte();
    short s = inputStream.readShort();
    int i = inputStream.readInt();
    long l = inputStream.readLong();
    float f = inputStream.readFloat();
    double d = inputStream.readDouble();

    // Check for end of stream:
    try {
      int value = inputStream.readByte();
      System.out.println("More input: " + value);
    } catch (EOFException eofe) {
      System.out.println("End of stream");
    } finally {
      // Close the input stream, which also closes the underlying stream.
      inputStream.close();
    }

    // Write the values read to the standard input stream:
    System.out.println("Values read:");
    System.out.println(v);
    System.out.println(c);
    System.out.println(b);
    System.out.println(s);
    System.out.println(i);
    System.out.println(l);
    System.out.println(f);
    System.out.println(d);
  }
コード例 #8
0
 /** @tests java.io.DataInputStream#DataInputStream(java.io.InputStream) */
 public void test_ConstructorLjava_io_InputStream() throws IOException {
   try {
     os.writeChar('t');
     os.close();
     openDataInputStream();
   } finally {
     dis.close();
   }
 }
コード例 #9
0
ファイル: UBJsonWriter.java プロジェクト: stbachmann/libgdx
 /**
  * Appends an optimized {@code char array} value to the stream. As an optimized array, the {@code
  * int16} value type marker and element count are encoded once at the array marker instead of
  * repeating the type marker for each element.
  *
  * @return this writer, for chaining
  */
 public UBJsonWriter value(char[] values) throws IOException {
   array();
   out.writeByte('$');
   out.writeByte('I');
   out.writeByte('#');
   value(values.length);
   for (int i = 0, n = values.length; i < n; i++) {
     out.writeChar(values[i]);
   }
   pop(true);
   return this;
 }
コード例 #10
0
    @Override
    public void run() {
      try {
        ArrayList<TCPConnection> timeout_list = new ArrayList<>();
        while (true) {
          timeout_list.clear();
          synchronized (connection_pool) {
            // We check the connections every 2 minutes,
            connection_pool.wait(2 * 60 * 1000);
            long time_now = System.currentTimeMillis();
            Set<ServiceAddress> s = connection_pool.keySet();
            // For each key entry,
            Iterator<ServiceAddress> i = s.iterator();
            while (i.hasNext()) {
              ServiceAddress addr = i.next();
              TCPConnection c = connection_pool.get(addr);
              //              System.out.println("CHECK: " + (c.last_lock_timestamp+(10*1000)) + " -
              // " + time_now);
              //              System.out.println("c.lock_count = " + c.lock_count);
              // If lock is 0, and past timeout, we can safely remove it.
              // The timeout on a connection is 5 minutes plus the poll artifact
              if (c.lock_count == 0 && c.last_lock_timestamp + (5 * 60 * 1000) < time_now) {

                i.remove();
                timeout_list.add(c);
              }
            }

            // If the thread was stopped, we finish the run method which stops
            // the thread.
            if (stopped) {
              return;
            }
          } // synchronized (connection_pool)

          // For each connection that timed out,
          for (TCPConnection c : timeout_list) {
            //            System.out.println("KILLING: " + c.s);
            DataOutputStream dout = new DataOutputStream(c.out);
            // Write the stream close message, and flush,
            try {
              dout.writeChar('e');
              dout.flush();
              c.s.close();
            } catch (IOException e) {
              log.log(Level.SEVERE, "Failed to dispose timed out connection", e);
            }
          }
        }
      } catch (InterruptedException e) {
        // Thread was killed,
      }
    }
コード例 #11
0
ファイル: MDAG.java プロジェクト: liuzl/HanLP
 @Override
 public void save(DataOutputStream out) throws Exception {
   simplify();
   out.writeInt(charTreeSet.size());
   for (Character character : charTreeSet) {
     out.writeChar(character);
   }
   simplifiedSourceNode.save(out);
   out.writeInt(mdagDataArray.length);
   for (SimpleMDAGNode simpleMDAGNode : mdagDataArray) {
     simpleMDAGNode.save(out);
   }
 }
コード例 #12
0
ファイル: DatLog.java プロジェクト: JohannaMaisel/DataMonitor
  /////// GPS status callback
  public void onGpsStatusChanged(int status) {
    DataOutputStream file = fout[2];
    long tim = System.currentTimeMillis();

    // Get the status
    GpsStatus lStatus = null;
    lStatus = mLocMan.getGpsStatus(null);

    if (status == GpsStatus.GPS_EVENT_FIRST_FIX) {
      mLV.addtext("GPS_EVENT_FIRST_FIX - TTFX =" + lStatus.getTimeToFirstFix());
    } else if (status == GpsStatus.GPS_EVENT_STARTED) {
      mLV.addtext("GPS_EVENT_STARTED " + tim);
    } else if (status == GpsStatus.GPS_EVENT_STOPPED) {
      mLV.addtext("GPS_EVENT_STOPPED " + tim);
    }

    if (lStatus != null) {
      if (file != null) {
        try {
          file.writeLong(tim);
          Iterable<GpsSatellite> satlist = lStatus.getSatellites();
          for (GpsSatellite sat : satlist) {
            file.writeInt(sat.getPrn());
            file.writeFloat(sat.getAzimuth());
            file.writeFloat(sat.getElevation());
            file.writeFloat(sat.getSnr());
            file.writeBoolean(sat.hasAlmanac());
            file.writeBoolean(sat.hasEphemeris());
            file.writeBoolean(sat.usedInFix());
            if (satlist.iterator().hasNext()) file.writeChar('@');
            else file.writeChar('#');
          }

        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
コード例 #13
0
ファイル: Scores.java プロジェクト: anod/SeaMerchantAndroid
 public void writeScore(Context ctx) {
   DataOutputStream out;
   try {
     out = new DataOutputStream(ctx.openFileOutput(FILENAME, Context.MODE_APPEND));
     out.writeInt(getScore());
     out.writeChar(' ');
     out.writeUTF(mName);
     out.flush();
     out.close();
   } catch (IOException e) {
     Debug.e(e);
   }
 }
コード例 #14
0
  /**
   * writeString
   *
   * @param output
   * @param text
   * @throws IOException
   */
  public static void writeString(DataOutputStream output, String text) throws IOException {
    if (text == null) {
      throw new IllegalArgumentException(Messages.FileUtilities_Text_Undefined);
    }

    char[] chars = text.toCharArray();
    int length = chars.length;

    output.writeInt(length);

    for (int i = 0; i < length; i++) {
      output.writeChar(chars[i]);
    }
  }
コード例 #15
0
  /**
   * Encodes a string using arithmetic encoding.
   *
   * @param message the message to encode
   * @return the encoded value as a byte array
   */
  @Override
  public byte[] encode(String message) {
    // Remove invalid UTF-8 symbols.
    message = message.replace(Character.toString((char) 0xFFFD), "");

    // Set up encoding process.
    BigInteger lowValue = BigInteger.valueOf(0);
    BigInteger highValue = BigInteger.valueOf(0);
    BigInteger length = BigInteger.valueOf(message.length());
    BigInteger totalProduct = BigInteger.valueOf(1);

    // Make the key based on the current string.
    CharMap key = makeKey(message);

    // Calculate the lowValue (the lowest possible encoding).
    for (Character c : message.toCharArray()) {
      lowValue = lowValue.add(totalProduct.multiply(BigInteger.valueOf(key.get(c))));
      lowValue = lowValue.multiply(length);
      totalProduct = totalProduct.multiply(BigInteger.valueOf(key.getProbability(c)));
    }
    lowValue = lowValue.divide(length);

    // Calculate the highValue based on the lowValue.
    highValue = lowValue.add(totalProduct);

    // Create a value for the final encoding
    BigInteger value = lowValue;
    value = maxZeroes(value, highValue);
    int zeroes = value.getLowestSetBit();
    value = value.shiftRight(zeroes);

    // Output the resulting number to a byte array.
    ByteArrayOutputStream outputBytes = new ByteArrayOutputStream();
    DataOutputStream output = new DataOutputStream(outputBytes);
    try {
      output.writeInt(key.size());
      output.writeInt(zeroes);
      for (Map.Entry<Character, Integer> e : key.entrySet()) {
        output.writeChar(e.getKey());
        output.writeInt(e.getValue());
      }
      output.write(value.toByteArray());
    } catch (java.io.IOException e) {
      System.err.println("There was an IOException.");
      return null;
    }

    // Return the output bytes.
    return outputBytes.toByteArray();
  }
コード例 #16
0
ファイル: Value.java プロジェクト: jihed-gasmi/crossbridge
 /**
  * Will write the given object as either a value or an untagged value to the DataOutputStream.
  *
  * @param os write the value here
  * @param obj the Object to write
  * @param tagged true if the value is tagged, false otherwise
  * @throws IOException
  * @throws InvalidFieldException
  */
 private static void writeValue(DataOutputStream os, Object obj, boolean tagged)
     throws IOException, JdwpException {
   Class clazz = obj.getClass();
   if (clazz.isPrimitive()) {
     if (clazz == byte.class) {
       if (tagged) os.writeByte(JdwpConstants.Tag.BYTE);
       os.writeByte(((Byte) obj).byteValue());
     } else if (clazz == char.class) {
       if (tagged) os.writeByte(JdwpConstants.Tag.CHAR);
       os.writeChar(((Character) obj).charValue());
     } else if (clazz == float.class) {
       if (tagged) os.writeByte(JdwpConstants.Tag.FLOAT);
       os.writeFloat(((Float) obj).floatValue());
     } else if (clazz == double.class) {
       if (tagged) os.writeByte(JdwpConstants.Tag.DOUBLE);
       os.writeDouble(((Double) obj).doubleValue());
     } else if (clazz == int.class) {
       if (tagged) os.writeByte(JdwpConstants.Tag.BYTE);
       os.writeInt(((Integer) obj).intValue());
     } else if (clazz == long.class) {
       if (tagged) os.writeByte(JdwpConstants.Tag.LONG);
       os.writeLong(((Long) obj).longValue());
     } else if (clazz == short.class) {
       if (tagged) os.writeByte(JdwpConstants.Tag.SHORT);
       os.writeInt(((Short) obj).shortValue());
     } else if (clazz == void.class) { // A 'void' has no data
       if (tagged) os.writeByte(JdwpConstants.Tag.VOID);
     } else if (clazz == boolean.class) {
       if (tagged) os.writeByte(JdwpConstants.Tag.BOOLEAN);
       os.writeBoolean(((Boolean) obj).booleanValue());
     } else { // This shouldn't be possible
       throw new JdwpInternalErrorException("Field has invalid primitive!");
     }
   } else {
     // Object is an Object, not a primitive type wrapped in an object
     // Write the appropriate tag
     if (tagged) {
       if (clazz.isArray()) os.writeByte(JdwpConstants.Tag.ARRAY);
       else if (obj instanceof String) os.writeByte(JdwpConstants.Tag.STRING);
       else if (obj instanceof Thread) os.writeByte(JdwpConstants.Tag.THREAD);
       else if (obj instanceof ThreadGroup) os.writeByte(JdwpConstants.Tag.THREAD_GROUP);
       else if (obj instanceof ClassLoader) os.writeByte(JdwpConstants.Tag.CLASS_LOADER);
       else if (obj instanceof Class) os.writeByte(JdwpConstants.Tag.CLASS_OBJECT);
       else os.writeByte(JdwpConstants.Tag.OBJECT);
     }
     ObjectId oid = VMIdManager.getDefault().getObjectId(obj);
     oid.write(os);
   }
 }
コード例 #17
0
  public byte[] convertEventToRawString(CriticalSectionEvent event) {
    try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DataOutputStream output = new DataOutputStream(byteArrayOutputStream)) {
      output.writeLong(event.getTime().getMillis());
      output.writeLong(event.getTime().getNanos());
      output.writeChar(event.discriminator());

      return byteArrayOutputStream.toByteArray();
    } catch (IOException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
      return new byte[0];
    }
  }
コード例 #18
0
 private void startGame() {
   try {
     writeMessage(0, player.getPlayerNumber());
     out.writeChar(player.getParty());
     out.writeInt(player.getIdealPt());
     out.writeInt(model.getBudget());
   } catch (IOException e1) {
     removePlayer();
   }
   writeChartData();
   ArrayList<Candidate> candidates = model.getCandidates();
   writeMessage(2, candidates.size());
   for (int i = 0; i < candidates.size(); i++) {
     try {
       out.writeByte(candidates.get(i).getCandidateNumber());
       out.writeByte(candidates.get(i).getParty());
     } catch (IOException e) {
       removePlayer();
     }
   }
 }
コード例 #19
0
ファイル: Test.java プロジェクト: seinlin/js2me
  public void startApp() {

    try {
      byte[] input = {
        -2, 54, -2, -2, 1, 0, -128, 1, 91, -64, 0x0C, 0x7A, -31, 0x47, -82, 0x14, 0x7B, 0x41, 0x09,
        0x1d, 0x25, 122, 121, 0, 120, -1, -7, 0x51, 0x54, -1, -1, -1, -1, -1, -7, 0x51, 0x54, -14,
        0x16, 0, 10, -59, -101, 99, 105, -61, -77, -59, -126, 107, 97
      };
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      DataOutputStream s = new DataOutputStream(out);
      s.write(254);
      byte[] bb = {54, -2};
      s.write(bb);
      s.write(bb, 1, 1);
      s.writeBoolean(true);
      s.writeBoolean(false);
      s.writeByte(-128);
      s.writeChar('ś');
      s.writeDouble(-3.56);
      s.writeFloat(8.569615f);
      s.writeChars("穹x");
      s.writeInt(-437932);
      s.writeLong(-437932l);
      s.writeShort(-3562);
      s.writeUTF("ściółka");
      s.flush();
      bb = out.toByteArray();
      compare(bb.length, input.length);
      for (int i = 0; i < bb.length; i++) {
        compare(bb[i], input[i]);
      }
      s.close();

    } catch (Exception e) {
      e.printStackTrace();
      check(false);
    }
    finish();
  }
コード例 #20
0
 public void writeChar(char val) throws IOException {
   dos.writeChar(val);
 }
コード例 #21
0
ファイル: DataInputStreamApp.java プロジェクト: sks40gb/zunk
  public static void main(String[] args) {
    String filename = "data-out.dat";
    String message = "Hi,您好!";

    // Write primitives to an output file
    try {
      DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
      //            DataOutputStream out =
      //                    new DataOutputStream(
      //                    new BufferedOutputStream(
      //                    new FileOutputStream(filename)));
      out.writeByte(127);
      out.writeShort(0xFFFF); // -1
      out.writeInt(0xABCD);
      out.writeLong(0x1234); // JDK 7 syntax
      out.writeFloat(11.22f);
      out.writeDouble(55.66);
      out.writeBoolean(true);
      out.writeBoolean(false);
      for (int i = 0; i < message.length(); i++) {
        out.writeChar(message.charAt(i));
      }
      out.writeChars(message);
      out.writeBytes(message);
      out.flush();
    } catch (IOException ex) {
      ex.printStackTrace();
    }

    // Read raw bytes and print in Hex
    try {
      BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));
      int inByte;
      while ((inByte = in.read()) != -1) {
        System.out.printf("%02X ", inByte); // Print Hex codes
      }
      System.out.printf("%n%n");
    } catch (IOException ex) {
      ex.printStackTrace();
    }

    // Read primitives
    try {
      DataInputStream in = new DataInputStream(new FileInputStream(filename));
      System.out.println("byte:    " + in.readByte());
      System.out.println("short:   " + in.readShort());
      System.out.println("int:     " + in.readInt());
      System.out.println("long:    " + in.readLong());
      System.out.println("float:   " + in.readFloat());
      System.out.println("double:  " + in.readDouble());
      System.out.println("boolean: " + in.readBoolean());
      System.out.println("boolean: " + in.readBoolean());

      System.out.print("char:    ");
      for (int i = 0; i < message.length(); i++) {
        System.out.print(in.readChar());
      }
      System.out.println();

      System.out.print("chars:   ");
      for (int i = 0; i < message.length(); i++) {
        System.out.print(in.readChar());
      }
      System.out.println();

      System.out.print("bytes:   ");
      for (int i = 0; i < message.length(); i++) {
        System.out.print((char) in.readByte());
      }
      System.out.println();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
コード例 #22
0
 public void write(DataOutputStream out) throws IOException {
   out.writeUTF(name);
   out.writeChar('\t');
   out.writeUTF(value.toString());
 }
コード例 #23
0
 @Override
 public void writeChar(int v) throws IOException {
   dos.writeChar(v);
 }
コード例 #24
0
ファイル: UBJsonWriter.java プロジェクト: stbachmann/libgdx
 /**
  * Appends a {@code char} value to the stream. Because, in Java, a {@code char} is 16 bytes, this
  * corresponds to the {@code int16} value type in the UBJSON specification.
  *
  * @return this writer, for chaining
  */
 public UBJsonWriter value(char value) throws IOException {
   checkName();
   out.writeByte('I');
   out.writeChar(value);
   return this;
 }
コード例 #25
0
 /** @tests java.io.DataInputStream#readChar() */
 public void test_readChar() throws IOException {
   os.writeChar('t');
   os.close();
   openDataInputStream();
   assertEquals("Incorrect char read", 't', dis.readChar());
 }
 @Override
 protected void doComposeBody(DataOutputStream dataOutput) throws Exception {
   dataOutput.writeChar(requestSequenceId);
   dataOutput.writeChar(requestId);
   dataOutput.write(new byte[] {result});
 }
コード例 #27
0
 public void writeTo(DataOutputStream out) throws IOException {
   out.writeBoolean(simple);
   out.writeInt(randomNum);
   out.writeUTF(entityClass.getName());
   if (!simple) {
     out.writeUTF(property);
     byte type = PrimitiveTypes.getClassByObject(value);
     out.writeByte((Byte) type);
     switch (type) {
       case PrimitiveTypes.TYPE_NULL:
         // write nothing;
         break;
       case PrimitiveTypes.TYPE_BOOLEAN:
         out.writeBoolean((Boolean) value);
         break;
       case PrimitiveTypes.TYPE_BYTE:
         out.writeByte((Byte) value);
         break;
       case PrimitiveTypes.TYPE_CHAR:
         out.writeChar((Character) value);
         break;
       case PrimitiveTypes.TYPE_DOUBLE:
         out.writeDouble((Double) value);
         break;
       case PrimitiveTypes.TYPE_FLOAT:
         out.writeFloat((Float) value);
         break;
       case PrimitiveTypes.TYPE_INT:
         out.writeInt((Integer) value);
         break;
       case PrimitiveTypes.TYPE_LONG:
         out.writeLong((Long) value);
         break;
       case PrimitiveTypes.TYPE_SHORT:
         out.writeShort((Short) value);
         break;
       case PrimitiveTypes.TYPE_STRING:
         String str = (String) value;
         if (str.length() > Short.MAX_VALUE) {
           out.writeBoolean(true);
           ObjectOutputStream oos = new ObjectOutputStream(out);
           try {
             oos.writeObject(str);
           } finally {
             oos.close();
           }
         } else {
           out.writeBoolean(false);
           out.writeUTF(str);
         }
         break;
       case PrimitiveTypes.TYPE_SERIALIZABLE:
         ObjectOutputStream oos = new ObjectOutputStream(out);
         try {
           oos.writeObject(value);
         } finally {
           oos.close();
         }
         break;
       default:
         // write nothing
     }
   }
 }
コード例 #28
0
    // implement thread pool here, what common variable are the 2 threads sharing?
    // where are the threads being started from? ANS: server constructor
    // control thread's execution
    public void run() {
      // send client message indicating its mark (X or O),
      // process messages from client
      try {
          /** ***********************************************************START RUN ** */
        displayMessage(
            "Player "
                + (playerNumber == PLAYER_X ? X_MARK : O_MARK)
                + " connected\n"); // ternary operator, x_mark true? or 0_mark false?
        // ie. someone has to be x and someone has to o

        output.writeChar(mark); // send player's mark// output = stream

        // send message indicating connection
        output.writeUTF(
            "Player "
                + (playerNumber == PLAYER_X ? "X connected\n" : "O connected, please wait\n"));

        // if player X, wait for another player to arrive
        if (mark == X_MARK) { // Only if we're player x
          output.writeUTF("Waiting for another player");

          // wait for player O
          try {
            synchronized (this) { // synchronised on this object
              while (suspended) // variable suspend is set to true, while it's true
              wait(); // once
            }
          }

          // process interruptions while waiting
          catch (InterruptedException exception) {
            exception.printStackTrace();
          }

          // send message that other player connected and
          // player X can make a move
          output.writeUTF("Other player connected. Your move.");
        }
        /** ************************************************************************** */

        // while game not over
        while (!isGameOver()) {
            /** *** MAIN LOOP MAIN LOOP MAIN LOOP MAIN LOOP MAIN LOOP * */
          try {
            int location = input.readInt(); // read something from stream
            // check for valid move
            if (validateAndMove(location, playerNumber)
                && !isGameOver()) { // returns true if it's a valid move
              displayMessage("\nlocation: " + location);
              output.writeUTF("Valid move."); // this thread to other client
            } else if (validateAndMove(location, playerNumber)) {
              output.writeUTF(whoIsWinner);
              output.writeInt(location);
            } else {
              output.writeUTF("Invalid move, try again");
            }
          }
          // end else
          catch (IOException ioException) {
            ioException.printStackTrace();
          }
        } // end while game over

        // output.writeUTF("game over you win");
        try {
          // output.writeUTF("Valid move.");// this thread to other client
          output.writeUTF(whoIsWinner);
        } catch (Exception e) {
          e.printStackTrace();
        }
        connection.close(); // close connection to client
      } // end try

      // process problems communicating with client
      catch (IOException ioException) {
        ioException.printStackTrace();
        System.exit(1);
      }
    } // end method run
コード例 #29
0
 /**
  * Writes a char value to this stream.
  *
  * @param value a <code>char</code> value to be written.
  * @param s prefix to use if this write is logged. A value of null prevents logging altogether.
  * @throws IOException if there was an IO error while writing
  */
 public void writeChar(char value, String s) throws IOException {
   if (ENABLE_VERBOSE && s != null && Log.verbose()) Log.log("out[string]   " + s + "=" + value);
   dos.writeChar(value);
 }
コード例 #30
0
  /**
   * @ast method
   * @aspect GenerateClassfile
   * @declaredat /home/uoji/JastAddJ/Java1.4Backend/GenerateClassfile.jrag:142
   */
  public void generateClassfile() {
    super.generateClassfile();
    String fileName = destinationPath() + File.separator + constantPoolName() + ".class";
    if (options().verbose()) System.out.println("Writing class file to " + fileName);
    try {
      ConstantPool cp = constantPool();
      // force building of constant pool
      cp.addClass(constantPoolName());
      cp.addClass("java/lang/Object");
      for (int i = 0; i < getNumSuperInterfaceId(); i++) {
        cp.addClass(getSuperInterfaceId(i).type().constantPoolName());
      }
      for (Iterator iter = bcFields().iterator(); iter.hasNext(); ) {
        FieldDeclaration field = (FieldDeclaration) iter.next();
        cp.addUtf8(field.name());
        cp.addUtf8(field.type().typeDescriptor());
        field.attributes();
      }
      for (Iterator iter = bcMethods().iterator(); iter.hasNext(); ) {
        Object obj = iter.next();
        if (obj instanceof MethodDecl) {
          MethodDecl m = (MethodDecl) obj;
          cp.addUtf8(m.name());
          cp.addUtf8(m.descName());
          m.attributes();
        }
      }
      attributes();

      if (hasClinit()) {
        cp.addUtf8("<clinit>");
        cp.addUtf8("()V");
        clinit_attributes();
      }

      // actual classfile generation
      File dest = new File(fileName);
      File parentFile = dest.getParentFile();
      if (parentFile != null) parentFile.mkdirs();

      FileOutputStream f = new FileOutputStream(fileName);
      DataOutputStream out = new DataOutputStream(new BufferedOutputStream(f));
      out.writeInt(magicHeader());
      out.writeChar(minorVersion());
      out.writeChar(majorVersion());
      cp.emit(out);
      int flags = flags();
      if (isNestedType()) flags = mangledFlags(flags);
      if (isInterfaceDecl()) flags |= Modifiers.ACC_INTERFACE;
      out.writeChar(flags);
      out.writeChar(cp.addClass(constantPoolName()));
      out.writeChar(cp.addClass("java/lang/Object"));
      if (getNumSuperInterfaceId() == 1 && getSuperInterfaceId(0).type().isObject())
        out.writeChar(0);
      else out.writeChar(getNumSuperInterfaceId());
      for (int i = 0; i < getNumSuperInterfaceId(); i++) {
        TypeDecl typeDecl = getSuperInterfaceId(i).type();
        if (typeDecl.isInterfaceDecl()) out.writeChar(cp.addClass(typeDecl.constantPoolName()));
      }
      Collection fields = bcFields();
      out.writeChar(fields.size());
      for (Iterator iter = fields.iterator(); iter.hasNext(); ) {
        FieldDeclaration field = (FieldDeclaration) iter.next();
        out.writeChar(field.flags());
        out.writeChar(cp.addUtf8(field.name()));
        out.writeChar(cp.addUtf8(field.type().typeDescriptor()));
        out.writeChar(field.attributes().size());
        for (Iterator itera = field.attributes().iterator(); itera.hasNext(); )
          ((Attribute) itera.next()).emit(out);
      }
      Collection methods = bcMethods();
      out.writeChar(methods.size() + (hasClinit() ? 1 : 0));
      for (Iterator iter = methods.iterator(); iter.hasNext(); ) {
        BodyDecl b = (BodyDecl) iter.next();
        b.generateMethod(out, cp);
      }
      if (hasClinit()) {
        out.writeChar(Modifiers.ACC_STATIC);
        out.writeChar(cp.addUtf8("<clinit>"));
        out.writeChar(cp.addUtf8("()V"));
        out.writeChar(clinit_attributes().size());
        for (Iterator itera = clinit_attributes().iterator(); itera.hasNext(); )
          ((Attribute) itera.next()).emit(out);
      }
      out.writeChar(attributes().size());
      for (Iterator itera = attributes().iterator(); itera.hasNext(); )
        ((Attribute) itera.next()).emit(out);

      out.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }