Beispiel #1
3
 void send(Scores scoreTable) {
   if (out == null) return;
   try {
     out.reset();
     out.writeObject(scoreTable);
     out.flush();
   } catch (Exception e) {
     ctrl.serverError("Scores Send error!");
   }
 }
Beispiel #2
1
 void send(TimeStamp timeStamp) {
   if (out == null) return;
   try {
     out.reset();
     out.writeObject(timeStamp);
     out.flush();
   } catch (Exception e) {
     ctrl.serverError("TimeStamp Send error!");
   }
 }
Beispiel #3
1
 void send(PlayersList players) {
   if (out == null) return;
   try {
     out.reset();
     out.writeObject(players);
     out.flush();
   } catch (Exception e) {
     ctrl.serverError("PlayersList Send error!");
   }
 }
 private void sendAll(Object message) {
   synchronized (oos) {
     try {
       for (ObjectOutputStream out : oos) {
         out.writeObject(message);
         out.reset();
       }
     } catch (IOException ignored) {
     }
   }
 }
Beispiel #5
0
  public void sendMessage(String name, Serializable message) throws IOException {
    setCall();

    try {
      if (!statics.isTeamRobot()) {
        throw new IOException("You are not on a team.");
      }
      byteStreamWriter.reset();
      ObjectOutputStream objectStreamWriter = new ObjectOutputStream(byteStreamWriter);

      objectStreamWriter.writeObject(message);
      objectStreamWriter.flush();
      byteStreamWriter.flush();
      final byte[] bytes = byteStreamWriter.toByteArray();

      objectStreamWriter.reset();
      if (bytes.length > MAX_MESSAGE_SIZE) {
        throw new IOException("Message too big. " + bytes.length + ">" + MAX_MESSAGE_SIZE);
      }
      commands.getTeamMessages().add(new TeamMessage(getName(), name, bytes));
    } catch (IOException e) {
      out.printStackTrace(e);
      throw e;
    }
  }
Beispiel #6
0
 private byte[] serialize() {
   byte[] result = null;
   ByteArrayOutputStream bos = new ByteArrayOutputStream(150000);
   try {
     //			GZIPOutputStream zos = new GZIPOutputStream(bos);
     ZipOutputStream zos = new ZipOutputStream(bos);
     // zos.setLevel(4);
     zos.putNextEntry(new ZipEntry("Object"));
     ObjectOutputStream oos = new ObjectOutputStream(zos);
     //			oos.writeInt(1);
     oos.writeObject(this);
     oos.flush();
     oos.reset();
     zos.closeEntry();
     zos.flush();
     result = bos.toByteArray();
     bos.reset();
     bos.close();
     zos.close();
     oos.close();
   } catch (IOException e) {
     log.severe("Failed to serialize MemoStorable: " + e.getMessage());
     log.severe(e.getCause().getMessage());
   }
   return result;
 }
Beispiel #7
0
  /**
   * Sorts the in-memory buffer
   *
   * @param write whether to write the sorted buffer to a temp file
   * @throws Exception if a problem occurs
   */
  protected void sortBuffer(boolean write) throws Exception {

    String msg = statusMessagePrefix() + "Sorting in memory buffer....";
    if (m_log != null) {
      m_log.statusMessage(msg);
      m_log.logMessage("[" + getCustomName() + "] " + msg);
    }

    Collections.sort(m_incrementalBuffer, m_sortComparator);

    if (!write) {
      return;
    }

    String tmpDir = m_tempDirectory;
    File tempFile = File.createTempFile("Sorter", ".tmp");

    if (tmpDir != null && tmpDir.length() > 0) {
      try {
        tmpDir = m_env.substitute(tmpDir);

        File tempDir = new File(tmpDir);
        if (tempDir.exists() && tempDir.canWrite()) {
          String filename = tempFile.getName();
          File newFile = new File(tmpDir + File.separator + filename);
          tempFile = newFile;
          tempFile.deleteOnExit();
        }
      } catch (Exception ex) {
      }
    }

    if (!m_stopRequested.get()) {

      m_bufferFiles.add(tempFile);
      FileOutputStream fos = new FileOutputStream(tempFile);
      // GZIPOutputStream gzo = new GZIPOutputStream(fos);
      BufferedOutputStream bos = new BufferedOutputStream(fos, 50000);
      ObjectOutputStream oos = new ObjectOutputStream(bos);

      msg = statusMessagePrefix() + "Writing buffer to temp file " + m_bufferFiles.size() + "...";
      if (m_log != null) {
        m_log.statusMessage(msg);
        m_log.logMessage("[" + getCustomName() + "] " + msg);
      }

      for (int i = 0; i < m_incrementalBuffer.size(); i++) {
        InstanceHolder temp = m_incrementalBuffer.get(i);
        temp.m_instance.setDataset(null);
        oos.writeObject(temp);
        if (i % (m_bufferSizeI / 10) == 0) {
          oos.reset();
        }
      }

      bos.flush();
      oos.close();
    }
    m_incrementalBuffer.clear();
  }
  /*------------------------------------------------------------ */
  protected Object encodeName(Object value) throws IOException {
    if (value instanceof Number
        || value instanceof String
        || value instanceof Boolean
        || value instanceof Date) {
      return value;
    } else if (value.getClass().equals(HashMap.class)) {
      BasicDBObject o = new BasicDBObject();
      for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
        if (!(entry.getKey() instanceof String)) {
          o = null;
          break;
        }
        o.append(encodeName(entry.getKey().toString()), encodeName(entry.getValue()));
      }

      if (o != null) return o;
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bout);
    out.reset();
    out.writeUnshared(value);
    out.flush();
    return bout.toByteArray();
  }
Beispiel #9
0
 public void enviar(ConexionPaquete paquete) throws IOException {
   synchronized (os_bloqueo) {
     os.reset();
     os.writeObject(paquete);
     os.flush();
   }
 }
 /**
  * sendet alle Spiele an den Client
  *
  * @throws IOException wenn die Sendung fehlschlägt
  */
 private void sendeVerfuegbareSpiele() throws IOException {
   if (toReset) out.reset();
   else toReset = true;
   out.writeObject(spiele);
   out.flush();
   System.out.println("written");
 }
 public static byte[] encodeValue(Object value) throws IOException {
   ByteArrayOutputStream bout = new ByteArrayOutputStream();
   ObjectOutputStream out = new ObjectOutputStream(bout);
   out.reset();
   out.writeUnshared(value);
   out.flush();
   return bout.toByteArray();
 }
Beispiel #12
0
 void send(GameInfo gameInfo) {
   if (out == null) return;
   try {
     out.reset();
     out.writeObject(gameInfo);
     out.flush();
   } catch (Exception e) {
     ctrl.serverError("GameInfo Send error!");
   }
 }
Beispiel #13
0
 /**
  * Send a message to client.
  *
  * @param msg
  */
 public void sendMsg(Object msg) {
   try {
     System.out.println(">> Escribir " + this.getUsername() + ": " + msg);
     out.reset();
     out.writeObject(msg);
     out.flush();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 /** java.io.ObjectOutputStream#reset() */
 public void test_reset() throws Exception {
   // Test for method void java.io.ObjectOutputStream.reset()
   String o = "HelloWorld";
   oos.writeObject(o);
   oos.writeObject(o);
   oos.reset();
   oos.writeObject(o);
   ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
   ois.close();
 }
  /**
   * Odošle celý zoznam lietadiel, ktoré sa na danom letisku nachádzajú klientovi.
   *
   * @throws EmptyRouteException Ak sa v trase lietadla už nenájde žiaden ďalší bod a lietadlo ešte
   *     nepristáva.
   * @throws WaypointNotLoadedException Ak sa v trase lietadla nepodarí nájsť bod, ktorý definuje
   *     letisková mapa ako nasledujúci bod na ním letenej trase.
   * @throws IOException Ak sa nepodarí odoslanie / prijatie dát klientnovi.
   */
  private void sendAircraftToClient(double timerDifference)
      throws IOException, EmptyRouteException, WaypointNotLoadedException {
    Random rand = new Random();
    int generatedAcftSize = generatedAircraft.size();
    if (generatedAcftSize < MAX_DEP_AIRCRAFT
        && checkRunwayClear()
        && (System.currentTimeMillis() % (rand.nextInt((generatedAcftSize + 1) * 30) + 1)) == 0) {
      System.out.println("Vygenerovalo sa nové lietadlo...");
      Aircraft acft = aircraftGenerator.generateRandomAircraft(rand.nextInt(2) > 0);
      acft.setLatitude(
          loadedAirport.getWaypointByName(requestedArptIcao.toUpperCase()).getPixelCoordX());
      acft.setLongitude(
          loadedAirport.getWaypointByName(requestedArptIcao.toUpperCase()).getPixelCoordY());
      generatedAircraft.add(acft);
      loadedAirport.setRunwayBlocked(true);
    }

    // Odoslanie aktuálneho zoznamu lietadiel na letisku
    outgoingData.writeObject(generatedAircraft);
    outgoingData.reset();

    synchronized (generatedAircraft) {
      // Modifikácia dát lietadiel na letisku
      for (int i = 0; i < generatedAircraft.size(); i++) {
        Aircraft acft = generatedAircraft.get(i);
        if (checkRunwayClear()) {
          loadedAirport.setRunwayBlocked(false);
          loadedAirport.setAircraftBlockingRunway("");
        }
        if (acft.isClearedForDeparture()) {
          moveAircraft(acft, timerDifference);
          accelerateAircraft(acft);
          climbAircraft(acft);
          if (isClearedToLand(acft)) {
            loadedAirport.setRunwayBlocked(true);
            loadedAirport.setAircraftBlockingRunway(acft.getCallSign());
          } else {
            if (acft.isAircraftLanding() && isWithinLandingDistance(acft)) {
              if (loadedAirport.isRunwayBlocked()
                  && !loadedAirport.getAircraftBlockingRunway().equals(acft.getCallSign())) {
                acft.getActualRoute()
                    .getRoutePoints()
                    .add(
                        loadedAirport
                            .getRandomWaypoint(requestedArptIcao.toUpperCase())
                            .toString());
                acft.setGoingAround(true);
              }
            }
          }
        }
      }
    }
  }
Beispiel #16
0
 private void send() {
   try {
     // Reset objectOutputStream
     out.reset();
     // Write arraylist of messages to outputStream
     out.writeObject(messages);
     // Flushes outputStream
     out.flush();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  public static void saveImage(AWTCanvas image, String file) throws IOException {
    FileOutputStream fos = new FileOutputStream(new File(file));
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    ObjectOutputStream oos = new ObjectOutputStream(bos);

    for (int i = 0; i < 1; i++) {
      oos.writeObject(image);
      oos.reset();
    }

    oos.close();
    bos.close();
  }
  /** send GameState to Client */
  private void sendGameState() {
    try {

      GameState gameState = dealer.getGameState();
      out.writeObject(gameState);
      out.flush();
      out.reset();

    } catch (IOException e) {
      e.printStackTrace();
      this.finalize();
    }
  }
Beispiel #19
0
 public void send(Message message) {
   try {
     String messageValue = MessageSerializer.writeMessage(message);
     if (ConfigSettings.instance().isDumpMessages()) {
       System.out.println("Send: " + messageValue);
     }
     out.writeUTF(messageValue);
     out.flush();
     out.reset();
   } catch (IOException ex) {
     ex.printStackTrace();
     receiver.interrupt();
   }
 }
Beispiel #20
0
 public void writeTurn(ITurnSnapshot turn, int round, int time) {
   try {
     if (time != recordInfo.turnsInRounds[round]) {
       throw new Error("Something rotten");
     }
     if (time == 0) {
       objectWriteStream.reset();
     }
     recordInfo.turnsInRounds[round]++;
     recordInfo.roundsCount = round + 1;
     objectWriteStream.writeObject(turn);
   } catch (IOException e) {
     logError(e);
   }
 }
  /**
   * we need to open a connection to the client and give it a token so we can identify it in the
   * future
   */
  public void initializeCLient() throws IOException {
    log.debug("initializing Client");
    this.out = new ObjectOutputStream(this.socket.getOutputStream());
    try {

      token = dealer.addPlayer(this);

    } catch (MaxPlayerException e) {
      System.out.println(e.getMessage());
      this.finalize();
    }
    log.debug("sending token");
    out.writeObject(token);
    out.flush();
    out.reset();
  }
Beispiel #22
0
  public static void main(String[] args) throws IOException {

    long start = System.currentTimeMillis();

    Socket s = new Socket("localhost", 4444);
    ObjectOutputStream toServer = new ObjectOutputStream(s.getOutputStream());

    Person p = new Person("John", 0);

    for (int id = 0; id < HowMany.times; id++) {
      p.setId(id);
      toServer.writeObject(p);

      toServer.reset();
    }

    long end = System.currentTimeMillis();
    System.out.println("Total time " + (end - start) / 1000 + "s");
  }
 private void write(T m) {
   try {
     if (m == null) {
       return;
     }
     objectOutputstreamTimes++;
     if (objectOutputstreamTimes == 2000) {
       dataFileOutputStream.reset();
       objectOutputstreamTimes = 1;
     }
     dataFileOutputStream.writeObject(m);
     dataFileOutputStream.flush();
     // 更新写入的偏移量
     fileMap.get(meta.getFileWriting()).incrementAndGet();
   } catch (Exception e) {
     log.error("write message failed", e);
     throw new RuntimeException("write message failed", e);
   }
 }
Beispiel #24
0
  /**
   * Constructor. Establishes a TCP socket connection with the DHCP client daemon on port 5818.
   *
   * @throws IOException if unable to establish the connection with the DHCP client daemon.
   */
  private Poller(long timeout) throws IOException {
    DhcpdConfigFactory dcf = DhcpdConfigFactory.getInstance();
    try {
      LOG.debug(
          "Poller.ctor: opening socket connection with DHCP client daemon on port {}",
          dcf.getPort());
      m_connection = new Socket(InetAddressUtils.addr("127.0.0.1"), dcf.getPort());

      LOG.debug("Poller.ctor: setting socket timeout to {}", timeout);
      m_connection.setSoTimeout((int) timeout);

      // Establish input/output object streams
      m_ins = new ObjectInputStream(m_connection.getInputStream());
      m_outs = new ObjectOutputStream(m_connection.getOutputStream());
      m_outs.reset();
      m_outs.flush();
    } catch (IOException ex) {
      LOG.error("IO Exception during socket connection establishment with DHCP client daemon.", ex);
      if (m_connection != null) {
        try {
          m_ins.close();
          m_outs.close();
          m_connection.close();
        } catch (Throwable t) {
        }
      }
      throw ex;
    } catch (Throwable t) {
      LOG.error(
          "Unexpected exception during socket connection establishment with DHCP client daemon.",
          t);
      if (m_connection != null) {
        try {
          m_ins.close();
          m_outs.close();
          m_connection.close();
        } catch (Throwable tx) {
        }
      }
      throw new UndeclaredThrowableException(t);
    }
  }
  @Override
  protected void append(E event) {

    if (event == null) return;

    if (address == null) {
      addError(
          "No remote host is set for SocketAppender named \""
              + this.name
              + "\". For more information, please visit http://logback.qos.ch/codes.html#socket_no_host");
      return;
    }

    if (oos != null) {
      try {
        postProcessEvent(event);
        Serializable serEvent = getPST().transform(event);
        oos.writeObject(serEvent);
        oos.flush();
        if (++counter >= CoreConstants.OOS_RESET_FREQUENCY) {
          counter = 0;
          // Failing to reset the object output stream every now and
          // then creates a serious memory leak.
          // System.err.println("Doing oos.reset()");
          oos.reset();
        }
      } catch (IOException e) {
        if (oos != null) {
          try {
            oos.close();
          } catch (IOException ignore) {
          }
        }

        oos = null;
        addWarn("Detected problem with connection: " + e);
        if (reconnectionDelay > 0) {
          fireConnector();
        }
      }
    }
  }
Beispiel #26
0
 @Override
 public void run() {
   // TODO Auto-generated method stub
   try {
     // Log.v("InsertClient spawned at " + Globals.myPort,"Message being sent " + wm.from +
     // wm.to+wm.key+wm.value +wm.type);
     Socket sendSock =
         new Socket(InetAddress.getByAddress(new byte[] {10, 0, 2, 2}), Integer.parseInt(wm.to));
     ObjectOutputStream nw = new ObjectOutputStream(sendSock.getOutputStream());
     nw.reset();
     nw.writeObject(wm);
     nw.flush();
     nw.close();
     sendSock.close();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     Log.e(" Insert client failed to send message at " + Globals.myPort, " to " + wm.to);
   }
   return;
 }
Beispiel #27
0
  public void streamingSerialization(List<EventWrapper<LoggingEvent>> loggingEvents)
      throws IOException, ClassNotFoundException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    startTest();
    int counter = 0;
    for (EventWrapper<LoggingEvent> current : loggingEvents) {
      oos.writeObject(current);
      if (++counter >= CoreConstants.OOS_RESET_FREQUENCY) {
        counter = 0;
        // Failing to reset the object output stream every now and
        // then creates a serious memory leak.
        // System.err.println("Doing oos.reset()");
        oos.reset();
      }
    }
    oos.flush();
    oos.close();
    byte[] bytes = bos.toByteArray();
    stopTest("streamingSerialization", "write", bytes.length, loggingEvents.size());
    if (logger.isDebugEnabled()) logger.debug("byteCounter: {}", bytes.length);

    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
    ObjectInputStream ois = new ObjectInputStream(bis);
    long dummy = 0;

    startTest();
    //noinspection ForLoopReplaceableByForEach
    for (int i = 0; i < loggingEvents.size(); i++) {
      Object obj = ois.readObject();
      dummy += obj.hashCode();
    }
    stopTest("streamingSerialization", "read", bytes.length, loggingEvents.size());
    ois.close();
    if (logger.isDebugEnabled()) logger.debug("Dummy: {}", dummy);
  }
Beispiel #28
0
 @Override
 public synchronized void run() {
   boolean bName = true;
   while (listening) {
     try {
       Object object = in.readObject();
       if (object.getClass().equals(Boolean.class)) {
         boolean can = (boolean) object;
         int nWay = (int) in.readObject();
         if (can) {
           int position = 0;
           synchronized (players) {
             for (int i = 0; i < players.size(); i++)
               if (players.get(i).getName().equals(player.getName())) {
                 position = i;
                 break;
               }
           }
           if (ways != null) {
             synchronized (ways) {
               if ((ways[position] + nWay) != 3) ways[position] = nWay;
             }
           }
         }
       } else if (object.getClass().equals(Player.class)) {
         player = (Player) object;
         if (bName) {
           bName = false;
           synchronized (players) {
             player = checkPlayerName(player);
             out.writeObject(player);
             out.reset();
             players.add(player);
           }
           sendAll(players);
           sendAll(Const.CHAT + "В комнату вошел игрок " + player.getName() + "\n");
         } else {
           synchronized (players) {
             for (Player p : players) {
               if (p.getName().equals(player.getName())) {
                 p.setReady(player.isReady());
                 p.setPositionOnMap(player.getPositionOnMap());
                 sendAll(players);
                 break;
               }
             }
           }
         }
       } else if (object.getClass().equals(String.class)) {
         String s = (String) object;
         if (s.startsWith(Const.START)) {
           if (checkPlayersPositions()) sendAll(Const.START);
           else
             sendAll(
                 Const.CHAT
                     + "<Сервер>:Начальные позиции всех "
                     + "игроков не должны совпадать\n");
         } else if (s.equals(Const.EXIT)) {
           throw new Exception("Выход игрока по нажатию кнопки");
         } else {
           sendAll(object);
         }
       } else {
         sendAll(object);
       }
     } catch (Exception e) {
       e.printStackTrace();
       synchronized (players) {
         for (Player p : players)
           if (p.getName().equals(player.getName())) {
             players.remove(p);
             break;
           }
       }
       synchronized (oos) {
         oos.remove(out);
       }
       sendAll(players);
       sendAll(Const.CHAT + "Игрок " + player.getName() + " покинул комнату\n");
       if (ServerController.gameIsStarted) thoughtOutPlayer();
       break;
     }
   }
 }
 @Override
 public void reset() throws IOException {
   out.reset();
 }
Beispiel #30
0
  public void run() {
    objects = new LinkedList<TestObject>();
    isRunning = true;
    try {
      host = InetAddress.getByName("127.0.0.1");
      Socket sock = new Socket(host, PORT_NUMBER);
      sock.setSoTimeout(timeout);
      ObjectInputStream input = new ObjectInputStream(sock.getInputStream());
      TestObject object;
      System.out.println("Client connected"); // !

      // populate the objects list with objects from the server until the server sends a null object
      while ((object = (TestObject) input.readObject()).getIndex() != -1) {
        objects.add(object);
      }

      System.out.println("IN THE CLIENT :"); // !
      // ! for testing purposes
      for (int i = 0; i < NUM_OBJECTS; i++) {
        System.out.println(
            "TestObject "
                + i
                + " :: "
                + objects.get(i).getStringData()
                + " , "
                + objects.get(i).getIndex()); // !
      }

      System.out.println("Client initialized"); // !
      ObjectOutputStream output = new ObjectOutputStream(sock.getOutputStream());
      while (isRunning) {
        Random rand = new Random();
        Thread.sleep(rand.nextInt(2000));

        int stringData = rand.nextInt(1000);
        int objIdx = rand.nextInt(NUM_OBJECTS);

        objects.get(objIdx).setStringData("" + stringData);
        System.out.println(">>>>A client SET a TestObject stringData to " + stringData); // !

        // update the server (and thus other clients)
        // ObjectOutputStream output = new ObjectOutputStream( sock.getOutputStream() );

        output.reset();
        output.writeObject(objects.get(objIdx));
        output.flush();
        System.out.println("client written to server"); // !
        // update this client with new information from the server
        // (probably want to make this a new thread in the future)
        TestObject inObj;
        try {
          // System.out.println("created input stream");//!
          int i = 0;
          do {
            i++;
            inObj = (TestObject) input.readObject();
            // System.out.println("read object");//!
            // need to somehow put this in a loop so it keeps reading object until
            // the server no longer needs to send any more objects
            objects.set(inObj.getIndex(), inObj);
            System.out.println(
                ">>>>A client RECEIVED a TestObject with a stringData to "
                    + inObj.getStringData()); // !
            if (i > 1)
              System.out.println(
                  "a client read multiple objects------------------------------" + i);
          } while (input.available() != 0);
        } catch (SocketTimeoutException e) {
          continue;
        }
      }

      sock.close();

    } catch (Exception e) {
      System.out.println("Client exception.");
      e.printStackTrace();
    }
  }