/// <summary> /// Creates "request" or "cancel" messages /// </summary> /// <param name="index">Zero-based piece index</param> /// <param name="begin">Zero-based offset within the piece</param> /// <param name="length">Specifies the requested (cancelled) block's length</param> public PeerMessage(PeerMessageType type, int index, int begin, int length) { if (!(type == PeerMessageType.request || type == PeerMessageType.cancel)) { throw new ArgumentException("Type of the message must be \"request\" or \"cancel\""); } messageType = type; msgContents = new byte[msgLenSpace + msgTypeSpace + msgIntSpace * 3]; Array.Copy(PeerConnection.HTONNTOH(BitConverter.GetBytes(13)), msgContents, msgLenSpace); msgContents[msgLenSpace] = (byte)messageType; Array.Copy(PeerConnection.HTONNTOH(BitConverter.GetBytes(index)), 0, msgContents, msgLenSpace + msgTypeSpace, msgIntSpace); Array.Copy(PeerConnection.HTONNTOH(BitConverter.GetBytes(begin)), 0, msgContents, msgLenSpace + msgTypeSpace + msgIntSpace, msgIntSpace); Array.Copy(PeerConnection.HTONNTOH(BitConverter.GetBytes(length)), 0, msgContents, msgLenSpace + msgTypeSpace + msgIntSpace * 2, msgIntSpace); this.pieceIndex = index; this.pieceOffset = begin; this.length = length; }
/// <summary> /// Creates a message with no payload (keep-alive, choke, unchoke, interested or not interested) /// </summary> /// <param name="type">Type of the message</param> /// <exception cref="ArgumentException">Thrown if passed message type must have a payload</exception> public PeerMessage(PeerMessageType type) { if (type == PeerMessageType.keepAlive) { msgContents = new byte[msgLenSpace]; } else if (type == PeerMessageType.choke || type == PeerMessageType.unchoke || type == PeerMessageType.interested || type == PeerMessageType.notInterested) { msgContents = new byte[msgLenSpace + msgTypeSpace]; Array.Copy(PeerConnection.HTONNTOH(BitConverter.GetBytes(1)), msgContents, msgLenSpace); msgContents[msgLenSpace] = (byte)type; } else { throw new ArgumentException($"This message type: {type.ToString()} must have non-empty payload"); } }