Esempio n. 1
0
  @Override
  public synchronized void send(String type, Object... data) {
    this.log("send(" + type + ", " + Arrays.asList(data) + ")");
    Vector<Object> packet = new Vector<Object>(2);
    packet.add(type);
    for (Object v : data) packet.add(v);

    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
      BencodingOutputStream bos = new BencodingOutputStream(baos);
      bos.writeCollection(packet);
      bos.flush();
      byte[] bytes = baos.toByteArray();
      bos.close();
      byte[] header = new byte[8];
      int packetSize = bytes.length;
      // (_, protocol_version, compression_level, packet_index, current_packet_size) =
      // struct.unpack_from('!cBBBL', read_buffer)
      header[0] = 'P';
      header[1] = 0;
      header[2] = 0;
      // big endian size as 4 bytes:
      for (int b = 0; b < 4; b++) header[4 + b] = (byte) ((packetSize >>> (24 - b * 8)) % 256);
      this.debug(
          "send(...) header=0x" + hexlify_raw(header) + ", payload is " + packetSize + " bytes");
      this.outputStream.write(header);
      this.outputStream.write(bytes);
      this.outputStream.flush();
    } catch (IOException e) {
      this.connectionBroken(e);
    }
  }