Exemple #1
0
  // Send File
  public void sendFile(String chunkName) throws IOException {
    OutputStream os = null;
    String currentDir = System.getProperty("user.dir");
    chunkName = currentDir + "/src/srcFile/" + chunkName;
    File myFile = new File(chunkName);

    byte[] arrby = new byte[(int) myFile.length()];

    try {
      FileInputStream fis = new FileInputStream(myFile);
      BufferedInputStream bis = new BufferedInputStream(fis);
      bis.read(arrby, 0, arrby.length);

      os = csocket.getOutputStream();
      System.out.println("Sending File.");
      os.write(arrby, 0, arrby.length);
      os.flush();
      System.out.println("File Sent.");
      //			os.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      //			os.close();
    }
  }
 public static void main(String[] arguments) {
   try {
     // read byte data into a byte buffer
     String data = "friends.dat";
     FileInputStream inData = new FileInputStream(data);
     FileChannel inChannel = inData.getChannel();
     long inSize = inChannel.size();
     ByteBuffer source = ByteBuffer.allocate((int) inSize);
     inChannel.read(source, 0);
     source.position(0);
     System.out.println("Original byte data:");
     for (int i = 0; source.remaining() > 0; i++) {
       System.out.print(source.get() + " ");
     }
     // convert byte data into character data
     source.position(0);
     Charset ascii = Charset.forName("US-ASCII");
     CharsetDecoder toAscii = ascii.newDecoder();
     CharBuffer destination = toAscii.decode(source);
     destination.position(0);
     System.out.println("\n\nNew character data:");
     for (int i = 0; destination.remaining() > 0; i++) {
       System.out.print(destination.get());
     }
     System.out.println();
   } catch (FileNotFoundException fne) {
     System.out.println(fne.getMessage());
   } catch (IOException ioe) {
     System.out.println(ioe.getMessage());
   }
 }
Exemple #3
0
 // Doesn't really need to be runnable
 public void run() {
   for (; ; ) {
     try {
       dispatch();
     } catch (IOException x) {
       x.printStackTrace();
     }
   }
 }
Exemple #4
0
 // send a message to the output stream
 void sendMessage(String msg) {
   try {
     out.writeObject(msg);
     out.flush();
     System.out.println("Send message: " + msg);
   } catch (IOException ioException) {
     ioException.printStackTrace();
   }
 }
  public void handle(SelectionKey sk) throws IOException {
    try {

      if (request == null) {
        if (!receive(sk)) return;
        rbb.flip();
        if (parse()) build();
        try {
          reply.prepare();
        } catch (IOException x) {
          reply.release();
          reply = new Reply(Reply.Code.NOT_FOUND, new StringContent(x));
          reply.prepare();
        }
        if (send()) {
          // More bytes remain to be written
          sk.interestOps(SelectionKey.OP_WRITE);
        } else {
          // Reply completely written; we're done
          if (cio.shutdown()) {
            cio.close();
            reply.release();
          }
        }
      } else {
        if (!send()) { // Should be rp.send()
          if (cio.shutdown()) {
            cio.close();
            reply.release();
          }
        }
      }
    } catch (IOException x) {
      String m = x.getMessage();
      if (!m.equals("Broken pipe") && !m.equals("Connection reset by peer")) {
        System.err.println("RequestHandler: " + x.toString());
      }

      try {
        /*
         * We had a failure here, so we'll try to be nice
         * before closing down and send off a close_notify,
         * but if we can't get the message off with one try,
         * we'll just shutdown.
         */
        cio.shutdown();
      } catch (IOException e) {
        // ignore
      }

      cio.close();
      if (reply != null) {
        reply.release();
      }
    }
  }
 private boolean send() throws IOException {
   try {
     return reply.send(cio);
   } catch (IOException x) {
     if (x.getMessage().startsWith("Resource temporarily")) {
       System.err.println("## RTA");
       return true;
     }
     throw x;
   }
 }
Exemple #7
0
  @Override
  public void run() {
    try {
      out = new ObjectOutputStream(csocket.getOutputStream());
      out.flush();
      in = new ObjectInputStream(csocket.getInputStream());

      // Look for chunks
      String currentDir = System.getProperty("user.dir");
      File folder = new File(currentDir + "/src/srcFile");
      File[] listOfFiles = folder.listFiles();
      int fileCount = 0;
      OutputStream os;
      for (int i = 0; i < listOfFiles.length; i++) {
        if (listOfFiles[i].isFile()
            && listOfFiles[i]
                .getName()
                .toLowerCase()
                .contains("chunk")) { // 0 1 10 11 12 13 14 2 20 21 22 23 3 4 5 ....
          fileCount++;
          String chunkName = listOfFiles[i].getName().toString();
          chunkId = chunkName.substring(chunkName.lastIndexOf('.') + 6);

          xPayload(chunkId);
          if ((connTo.equals("2") && Integer.parseInt(chunkId) % noDev == 0)
              || (connTo.equals("3") && (Integer.parseInt(chunkId) - 1) % noDev == 0)
              || (connTo.equals("4") && (Integer.parseInt(chunkId) - 2) % noDev == 0)
              || (connTo.equals("5") && (Integer.parseInt(chunkId) - 3) % noDev == 0)
              || (connTo.equals("6") && (Integer.parseInt(chunkId) - 4) % noDev == 0)) {

            System.out.println(chunkName);
            sendFile(chunkName);
          }
        }
      }

      xPayload("-1");
      System.out.println("All chunks sent.");

    } catch (IOException ioException) {
      ioException.printStackTrace();
    } finally {
      // Close connections
      try {
        in.close();
        out.close();
        csocket.close();
        System.out.println("Thread closed.");
      } catch (IOException ioException) {
        System.out.println("Client " + devId + " disconnected.");
      }
    }
  }
 public long startTcpServer(SocketAddress sa) throws EmReactorException {
   try {
     ServerSocketChannel server = ServerSocketChannel.open();
     server.configureBlocking(false);
     server.socket().bind(sa);
     long s = createBinding();
     Acceptors.put(s, server);
     server.register(mySelector, SelectionKey.OP_ACCEPT, s);
     return s;
   } catch (IOException e) {
     throw new EmReactorException("unable to open socket acceptor: " + e.toString());
   }
 }
Exemple #9
0
 /**
  * Closes open files and resources associated with the open DDSImage. No other methods may be
  * called on this object once this is called.
  */
 public void close() {
   try {
     if (chan != null) {
       chan.close();
       chan = null;
     }
     if (fis != null) {
       fis.close();
       fis = null;
     }
     buf = null;
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Exemple #10
0
 public void run() {
   for (; ; ) {
     try {
       int n = sel.select();
       if (n > 0) processSelectedKeys();
       processPendingTargets();
       if (shutdown) {
         sel.close();
         return;
       }
     } catch (IOException x) {
       x.printStackTrace();
     }
   }
 }
 public void run() {
   while (!shutdown) {
     try {
       registerTargets();
       if (selector.select() > 0) {
         processSelectedKeys();
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   try {
     selector.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 public void receiveTarget() {
   // 接收用户输入的地址,向targets队列中加入任务
   try {
     BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
     String msg = null;
     while ((msg = localReader.readLine()) != null) {
       if (!msg.equals("bye")) {
         Target target = new Target(msg);
         addTarget(target);
       } else {
         shutdown = true;
         selector.wakeup();
         break;
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  public void registerTargets() {
    // 取出targets队列中的任务,向Selector注册连接就绪事件
    synchronized (targets) {
      while (targets.size() > 0) {
        Target target = (Target) targets.removeFirst();

        try {
          target.channel.register(selector, SelectionKey.OP_CONNECT, target);
        } catch (IOException x) {
          try {
            target.channel.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
          target.failure = x;
          addFinishedTarget(target);
        }
      }
    }
  }
Exemple #14
0
  /** @param args */
  public static void main(String[] args) {
    FileChannel fc = null;
    RandomAccessFile raf = null;
    // StringBuilder sb;

    if (args.length != 1) {
      System.out.println("Usage: Ntfs filename");
      System.exit(1);
    }
    /*
    sb = new StringBuilder();
    int[] foo = {129,4,229,33};
    for (int b: foo) {
        sb.insert(0,String.format("%02X", b));
    }
    System.out.println(sb.toString());
    System.exit(0);
    */
    try {
      raf = new RandomAccessFile(args[0], "r");
      fc = raf.getChannel();
      Filesystem fs = new Filesystem(fc);

      fs.demo();
      // fs.displayFs();
    } catch (FileNotFoundException x) {
      System.out.println("FNF exp: " + x.getMessage());
    } catch (IOException x) {
      System.out.println("IO exp: " + x.getMessage());
    } finally {
      if (raf != null)
        try {
          raf.close();
        } catch (IOException e) {
          e.printStackTrace(); // To change body of catch statement use File | Settings | File
          // Templates.
        }
    }
  }
  void isAcceptable(SelectionKey k) {
    ServerSocketChannel ss = (ServerSocketChannel) k.channel();
    SocketChannel sn;
    long b;

    for (int n = 0; n < 10; n++) {
      try {
        sn = ss.accept();
        if (sn == null) break;
      } catch (IOException e) {
        e.printStackTrace();
        k.cancel();

        ServerSocketChannel server = Acceptors.remove(k.attachment());
        if (server != null)
          try {
            server.close();
          } catch (IOException ex) {
          }
        ;
        break;
      }

      try {
        sn.configureBlocking(false);
      } catch (IOException e) {
        e.printStackTrace();
        continue;
      }

      b = createBinding();
      EventableSocketChannel ec = new EventableSocketChannel(sn, b, mySelector);
      Connections.put(b, ec);
      NewConnections.add(b);

      eventCallback(((Long) k.attachment()).longValue(), EM_CONNECTION_ACCEPTED, null, b);
    }
  }
  void checkIO() {
    long timeout;

    if (NewConnections.size() > 0) {
      timeout = -1;
    } else if (!Timers.isEmpty()) {
      long now = new Date().getTime();
      long k = Timers.firstKey();
      long diff = k - now;

      if (diff <= 0) timeout = -1; // don't wait, just poll once
      else timeout = diff;
    } else {
      timeout = 0; // wait indefinitely
    }

    try {
      if (timeout == -1) mySelector.selectNow();
      else mySelector.select(timeout);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemple #17
0
  // Exchange chunkId, devId, and ownedChunkArray
  void xPayload(String chunkId) {
    Socket conn = null;
    try {

      // Get message
      Object[] rPayload = (Object[]) in.readObject();
      chunkOwnedClientArray = (String[]) rPayload[1];
      connTo = (String) rPayload[0];
      chunkOwnedClientList = Arrays.asList(chunkOwnedClientArray);

      // Send Message
      Object[] payload = {chunkId, devId, chunkOwnedArray, filename};

      out.writeObject(payload);
      out.flush();
      System.out.println("chunkId being sent: " + chunkId + ", connected to: " + connTo);

    } catch (IOException ioException) {
      ioException.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
  public long connectTcpServer(String bindAddr, int bindPort, String address, int port) {
    long b = createBinding();

    try {
      SocketChannel sc = SocketChannel.open();
      sc.configureBlocking(false);
      if (bindAddr != null) sc.socket().bind(new InetSocketAddress(bindAddr, bindPort));

      EventableSocketChannel ec = new EventableSocketChannel(sc, b, mySelector);

      if (sc.connect(new InetSocketAddress(address, port))) {
        // Connection returned immediately. Can happen with localhost connections.
        // WARNING, this code is untested due to lack of available test conditions.
        // Ought to be be able to come here from a localhost connection, but that
        // doesn't happen on Linux. (Maybe on FreeBSD?)
        // The reason for not handling this until we can test it is that we
        // really need to return from this function WITHOUT triggering any EM events.
        // That's because until the user code has seen the signature we generated here,
        // it won't be able to properly dispatch them. The C++ EM deals with this
        // by setting pending mode as a flag in ALL eventable descriptors and making
        // the descriptor select for writable. Then, it can send UNBOUND and
        // CONNECTION_COMPLETED on the next pass through the loop, because writable will
        // fire.
        throw new RuntimeException("immediate-connect unimplemented");
      } else {
        ec.setConnectPending();
        Connections.put(b, ec);
        NewConnections.add(b);
      }
    } catch (IOException e) {
      // Can theoretically come here if a connect failure can be determined immediately.
      // I don't know how to make that happen for testing purposes.
      throw new RuntimeException("immediate-connect unimplemented: " + e.toString());
    }
    return b;
  }
  /** {@inheritDoc} */
  @SuppressWarnings("ErrorNotRethrown")
  @Override
  public IpcEndpoint accept() throws IgniteCheckedException {
    while (!Thread.currentThread().isInterrupted()) {
      Socket sock = null;

      boolean accepted = false;

      try {
        sock = srvSock.accept();

        accepted = true;

        InputStream inputStream = sock.getInputStream();
        ObjectInputStream in = new ObjectInputStream(inputStream);

        ObjectOutputStream out = new ObjectOutputStream(sock.getOutputStream());

        IpcSharedMemorySpace inSpace = null;

        IpcSharedMemorySpace outSpace = null;

        boolean err = true;

        try {
          IpcSharedMemoryInitRequest req = (IpcSharedMemoryInitRequest) in.readObject();

          if (log.isDebugEnabled()) log.debug("Processing request: " + req);

          IgnitePair<String> p = inOutToken(req.pid(), size);

          String file1 = p.get1();
          String file2 = p.get2();

          assert file1 != null;
          assert file2 != null;

          // Create tokens.
          new File(file1).createNewFile();
          new File(file2).createNewFile();

          if (log.isDebugEnabled()) log.debug("Created token files: " + p);

          inSpace = new IpcSharedMemorySpace(file1, req.pid(), pid, size, true, log);

          outSpace = new IpcSharedMemorySpace(file2, pid, req.pid(), size, false, log);

          IpcSharedMemoryClientEndpoint ret =
              new IpcSharedMemoryClientEndpoint(inSpace, outSpace, log);

          out.writeObject(
              new IpcSharedMemoryInitResponse(
                  file2, outSpace.sharedMemoryId(), file1, inSpace.sharedMemoryId(), pid, size));

          err = !in.readBoolean();

          endpoints.add(ret);

          return ret;
        } catch (UnsatisfiedLinkError e) {
          throw IpcSharedMemoryUtils.linkError(e);
        } catch (IOException e) {
          if (log.isDebugEnabled())
            log.debug(
                "Failed to process incoming connection "
                    + "(was connection closed by another party):"
                    + e.getMessage());
        } catch (ClassNotFoundException e) {
          U.error(log, "Failed to process incoming connection.", e);
        } catch (ClassCastException e) {
          String msg =
              "Failed to process incoming connection (most probably, shared memory "
                  + "rest endpoint has been configured by mistake).";

          LT.warn(log, null, msg);

          sendErrorResponse(out, e);
        } catch (IpcOutOfSystemResourcesException e) {
          if (!omitOutOfResourcesWarn) LT.warn(log, null, OUT_OF_RESOURCES_MSG);

          sendErrorResponse(out, e);
        } catch (IgniteCheckedException e) {
          LT.error(log, e, "Failed to process incoming shared memory connection.");

          sendErrorResponse(out, e);
        } finally {
          // Exception has been thrown, need to free system resources.
          if (err) {
            if (inSpace != null) inSpace.forceClose();

            // Safety.
            if (outSpace != null) outSpace.forceClose();
          }
        }
      } catch (IOException e) {
        if (!Thread.currentThread().isInterrupted() && !accepted)
          throw new IgniteCheckedException("Failed to accept incoming connection.", e);

        if (!closed)
          LT.error(
              log, null, "Failed to process incoming shared memory connection: " + e.getMessage());
      } finally {
        U.closeQuiet(sock);
      }
    } // while

    throw new IgniteInterruptedCheckedException("Socket accept was interrupted.");
  }
Exemple #20
0
  /** The listening thread's run method. */
  @Override
  public void run() {
    DatagramPacket packet = null;

    while (this.running) {
      try {
        IceSocketWrapper localSock;

        synchronized (sockLock) {
          if (!running) return;

          localSock = this.sock;
        }

        /*
         * Make sure localSock's receiveBufferSize is taken into
         * account including after it gets changed.
         */
        int receiveBufferSize = 1500;
        /*
        if(localSock.getTCPSocket() != null)
        {
            receiveBufferSize = localSock.getTCPSocket().
                getReceiveBufferSize();
        }
        else if(localSock.getUDPSocket() != null)
        {
            receiveBufferSize = localSock.getUDPSocket().
                getReceiveBufferSize();
        }
        */

        if (packet == null) {
          packet = new DatagramPacket(new byte[receiveBufferSize], receiveBufferSize);
        } else {
          byte[] packetData = packet.getData();

          if ((packetData == null) || (packetData.length < receiveBufferSize)) {
            packet.setData(new byte[receiveBufferSize], 0, receiveBufferSize);
          } else {
            /*
             * XXX Tell the packet it is large enough because the
             * socket will not look at the length of the data array
             * property and will just respect the length property.
             */
            packet.setLength(receiveBufferSize);
          }
        }

        localSock.receive(packet);

        // get lost if we are no longer running.
        if (!running) return;

        logger.finest("received datagram");

        RawMessage rawMessage =
            new RawMessage(
                packet.getData(),
                packet.getLength(),
                new TransportAddress(
                    packet.getAddress(), packet.getPort(), listenAddress.getTransport()),
                listenAddress);

        messageQueue.add(rawMessage);
      } catch (SocketException ex) {
        if (running) {
          logger.log(
              Level.WARNING, "Connector died: " + listenAddress + " -> " + remoteAddress, ex);

          stop();
          // Something wrong has happened
          errorHandler.handleFatalError(
              this, "A socket exception was thrown" + " while trying to receive a message.", ex);
        } else {
          // The exception was most probably caused by calling
          // this.stop().
        }
      } catch (ClosedChannelException cce) {
        logger.log(Level.WARNING, "A net access point has gone useless:", cce);

        stop();
        errorHandler.handleFatalError(
            this, "ClosedChannelException occurred while listening" + " for messages!", cce);
      } catch (IOException ex) {
        logger.log(Level.WARNING, "A net access point has gone useless:", ex);

        errorHandler.handleError(ex.getMessage(), ex);
        // do not stop the thread;
      } catch (Throwable ex) {
        logger.log(Level.WARNING, "A net access point has gone useless:", ex);

        stop();
        errorHandler.handleFatalError(
            this, "Unknown error occurred while listening for messages!", ex);
      }
    }
  }
    public void run() {
      // Here's where everything happens. The select method will
      // return when any operations registered above have occurred, the
      // thread has been interrupted, etc.
      try {
        while (!stop) {
          try {
            if (selector.select() > 0) {
              if (stop) {
                break;
              }
              // Someone is ready for I/O, get the ready keys
              Set readyKeys = selector.selectedKeys();
              Iterator it = readyKeys.iterator();

              // Walk through the ready keys collection and process date requests.
              while (it.hasNext()) {
                SelectionKey sk = (SelectionKey) it.next();
                it.remove();
                SocketChannel readChannel = null;
                TcpAddress incomingAddress = null;
                if (sk.isAcceptable()) {
                  // The key indexes into the selector so you
                  // can retrieve the socket that's ready for I/O
                  ServerSocketChannel nextReady = (ServerSocketChannel) sk.channel();
                  // Accept the date request and send back the date string
                  Socket s = nextReady.accept().socket();
                  readChannel = s.getChannel();
                  readChannel.configureBlocking(false);
                  readChannel.register(selector, SelectionKey.OP_READ);

                  incomingAddress = new TcpAddress(s.getInetAddress(), s.getPort());
                  SocketEntry entry = new SocketEntry(incomingAddress, s);
                  sockets.put(incomingAddress, entry);
                  timeoutSocket(entry);
                  TransportStateEvent e =
                      new TransportStateEvent(
                          DefaultTcpTransportMapping.this,
                          incomingAddress,
                          TransportStateEvent.STATE_CONNECTED,
                          null);
                  fireConnectionStateChanged(e);
                } else if (sk.isReadable()) {
                  readChannel = (SocketChannel) sk.channel();
                  incomingAddress =
                      new TcpAddress(
                          readChannel.socket().getInetAddress(), readChannel.socket().getPort());
                } else if (sk.isWritable()) {
                  try {
                    SocketEntry entry = (SocketEntry) sk.attachment();
                    SocketChannel sc = (SocketChannel) sk.channel();
                    if (entry != null) {
                      writeMessage(entry, sc);
                    }
                  } catch (IOException iox) {
                    if (logger.isDebugEnabled()) {
                      iox.printStackTrace();
                    }
                    logger.warn(iox);
                    TransportStateEvent e =
                        new TransportStateEvent(
                            DefaultTcpTransportMapping.this,
                            incomingAddress,
                            TransportStateEvent.STATE_DISCONNECTED_REMOTELY,
                            iox);
                    fireConnectionStateChanged(e);
                    sk.cancel();
                  }
                } else if (sk.isConnectable()) {
                  try {
                    SocketEntry entry = (SocketEntry) sk.attachment();
                    SocketChannel sc = (SocketChannel) sk.channel();
                    if ((!sc.isConnected()) && (sc.finishConnect())) {
                      sc.configureBlocking(false);
                      logger.debug("Connected to " + entry.getPeerAddress());
                      // make sure conncetion is closed if not used for timeout
                      // micro seconds
                      timeoutSocket(entry);
                      sc.register(selector, SelectionKey.OP_WRITE, entry);
                    }
                    TransportStateEvent e =
                        new TransportStateEvent(
                            DefaultTcpTransportMapping.this,
                            incomingAddress,
                            TransportStateEvent.STATE_CONNECTED,
                            null);
                    fireConnectionStateChanged(e);
                  } catch (IOException iox) {
                    if (logger.isDebugEnabled()) {
                      iox.printStackTrace();
                    }
                    logger.warn(iox);
                    sk.cancel();
                  }
                }

                if (readChannel != null) {
                  try {
                    readMessage(sk, readChannel, incomingAddress);
                  } catch (IOException iox) {
                    // IO exception -> channel closed remotely
                    if (logger.isDebugEnabled()) {
                      iox.printStackTrace();
                    }
                    logger.warn(iox);
                    sk.cancel();
                    readChannel.close();
                    TransportStateEvent e =
                        new TransportStateEvent(
                            DefaultTcpTransportMapping.this,
                            incomingAddress,
                            TransportStateEvent.STATE_DISCONNECTED_REMOTELY,
                            iox);
                    fireConnectionStateChanged(e);
                  }
                }
              }
            }
          } catch (NullPointerException npex) {
            // There seems to happen a NullPointerException within the select()
            npex.printStackTrace();
            logger.warn("NullPointerException within select()?");
          }
          processPending();
        }
        if (ssc != null) {
          ssc.close();
        }
      } catch (IOException iox) {
        logger.error(iox);
        lastError = iox;
      }
      if (!stop) {
        stop = true;
        synchronized (DefaultTcpTransportMapping.this) {
          server = null;
        }
      }
    }