Beispiel #1
0
 /**
  * Helper method to run a specified task and automatically handle the closing of the stream.
  *
  * @param <S>
  * @param task
  * @param errorHandler
  */
 public static <S extends Closeable> void closeOnComplete(
     S stream, StreamTask<S> task, StreamErrorHandler errorHandler) {
   try {
     task.execute(stream);
   } catch (Throwable t) {
     errorHandler.handle(t);
   } finally {
     if (stream != null) {
       try {
         stream.close();
       } catch (final IOException ignore) {
         if (log.isLoggable(Level.FINER)) {
           log.finer("Could not close stream due to: " + ignore.getMessage() + "; ignoring");
         }
       }
     }
   }
 }
  private int writeBuffer(
      S session, WriteRequest req, boolean hasFragmentation, int maxLength, long currentTime)
      throws Exception {
    IoBuffer buf = (IoBuffer) req.getMessage();
    int localWrittenBytes = 0;

    if (buf.hasRemaining()) {
      int length;

      if (hasFragmentation) {
        length = Math.min(buf.remaining(), maxLength);
      } else {
        length = buf.remaining();
      }

      try {
        localWrittenBytes = write(session, buf, length);
      } catch (IOException ioe) {
        // We have had an issue while trying to send data to the
        // peer : let's close the session.
        session.close(true);
      }
    }

    session.increaseWrittenBytes(localWrittenBytes, currentTime);

    if (!buf.hasRemaining() || (!hasFragmentation && (localWrittenBytes != 0))) {
      // Buffer has been sent, clear the current request.
      int pos = buf.position();
      buf.reset();

      fireMessageSent(session, req);

      // And set it back to its position
      buf.position(pos);
    }

    return localWrittenBytes;
  }
Beispiel #3
0
 void serv(int i) {
   try {
     S = new DatagramSocket(i);
     S.setSoTimeout(5000);
   } catch (Exception exception) {
     exception.printStackTrace();
     if (S != null)
       try {
         S.close();
       } catch (Exception exception2) {
       }
     return;
   }
   System.out.println(DF.format(new Date()) + "Waiting connections ...");
   do
     try {
       buf = new byte[256];
       P = new DatagramPacket(buf, buf.length);
       S.receive(P);
       Connection connection =
           (Connection) Connections.get(P.getAddress().toString() + P.getPort());
       if (connection == null) {
         System.out.println(
             DF.format(new Date())
                 + "Connect from "
                 + " ("
                 + P.getAddress().getHostAddress()
                 + ")");
         connection = new Connection(this, P);
         Connections.put(P.getAddress().toString() + P.getPort(), connection);
         connection.start();
       } else {
         connection.packet(P);
       }
     } catch (Exception exception1) {
     }
   while (true);
 }