Java tutorial
/* * Copyright 2014 Napolov Dmitry * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.aotorrent.common.protocol.peer; import io.netty.buffer.ByteBuf; import org.aotorrent.common.Torrent; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Arrays; /** * User: dnapolov * Date: 2/21/14 * Time: 5:37 PM */ public class HandshakeRequest implements PeerRequest { private static final String DEFAULT_PROTOCOL_STRING = "BitTorrent protocol"; private static final byte[] DEFAULT_RESERVED_BITS = { 0, 0, 0, 0, 0, 0, 0, 0 }; private final String protocolString; private final byte[] reserved; private final byte[] infoHash; private final byte[] peerId; public HandshakeRequest(ByteBuf message) throws UnsupportedEncodingException { int protocolStringLength = message.readUnsignedByte(); byte[] protocolStringBytes = new byte[protocolStringLength]; message.readBytes(protocolStringLength); this.protocolString = new String(protocolStringBytes, Torrent.DEFAULT_TORRENT_ENCODING); this.reserved = new byte[8]; message.readBytes(this.reserved); this.infoHash = new byte[Torrent.INFO_HASH_LENGTH]; message.readBytes(this.infoHash); this.peerId = new byte[Torrent.PEER_ID_LENGTH]; message.readBytes(this.peerId); } public HandshakeRequest(byte[] infoHash, byte[] peerId) { this(DEFAULT_PROTOCOL_STRING, DEFAULT_RESERVED_BITS, infoHash, peerId); } public HandshakeRequest(String protocolString, byte[] reserved, byte[] infoHash, byte[] peerId) { this.protocolString = protocolString; this.reserved = reserved; this.infoHash = infoHash; this.peerId = peerId; } @Override public RequestType getType() { return RequestType.HANDSHAKE; } @Override public byte[] toTransmit() throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); os.write(protocolString.length()); os.write(protocolString.getBytes(Torrent.DEFAULT_TORRENT_ENCODING)); os.write(reserved); os.write(infoHash); os.write(peerId); return os.toByteArray(); } public byte[] getInfoHash() { return infoHash; } @Override public String toString() { return "HandshakeRequest{" + "protocolString='" + protocolString + '\'' + ", reserved=" + Arrays.toString(reserved) + ", infoHash=" + Arrays.toString(infoHash) + ", peerId=" + Arrays.toString(peerId) + '}'; } }