Esempio n. 1
0
  @Override
  public boolean handleRead(SocketChannel ch, ByteBuffer buf, int nread) {
    try {
      while (buf.hasRemaining()) {
        byte request = buf.get();

        switch (request) {
          case 0x1A:
            {
              ByteBuffer out = ByteBuffer.allocate(1024);
              out.putInt(m_peers.size());

              Iterator it = m_peers.iterator();
              while (it.hasNext()) {
                PeerInfo info = (PeerInfo) it.next();

                out.put(info.address.getAddress());
                out.putInt(info.port);
              }

              m_server.send(ch, out.array());
              break;
            }
          case 0x1B:
            {
              PeerInfo info = new PeerInfo();
              info.port = buf.getInt();
              info.address = ch.socket().getInetAddress();

              Iterator it = m_peers.iterator();
              while (it.hasNext()) {
                PeerInfo i = (PeerInfo) it.next();
                if (i.port == info.port && i.address.equals(info.address)) return false;
              }

              m_peers.add(info);
              break;
            }
          default:
            return false;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }

    return true;
  }