private void ProcessAnyMessages() { try { IO.Stream reader = this.buffer.Reader; while (this.buffer.DataAvailable >= 5) { int length; PeerMessage message; peerProtocol.ReadMessageHeader(reader, out length, out message); if (length > 0) { if (length - 1 > buffer.DataAvailable) { reader.Seek(-5, IO.SeekOrigin.Current); break; } else { length--; // Config.LogDebugMessage("Message received: " + message.ToString() + " from " + this.ToString()); switch (message) { case PeerMessage.Bitfield: { this.piecesDownloaded = peerProtocol.ReadBitfieldMessage(reader, length); this.piecesDownloaded.SetLength(this.infofile.PieceCount); if (this.BitfieldChange != null) { this.BitfieldChange(this, -1); } } break; case PeerMessage.Choke: this.heisChoking = true; if (this.HeIsChokingChange != null) { this.HeIsChokingChange(this, this.heisChoking); } break; case PeerMessage.Unchoke: this.heisChoking = false; if (this.HeIsChokingChange != null) { this.HeIsChokingChange(this, this.heisChoking); } break; case PeerMessage.Interested: this.heisInterested = true; if (this.HeIsInterestedChange != null) { this.HeIsInterestedChange(this, this.heisInterested); } break; case PeerMessage.Uninterested: this.heisInterested = false; if (this.HeIsInterestedChange != null) { this.HeIsInterestedChange(this, this.heisInterested); } break; case PeerMessage.Have: { // update piecesdownloaded int pieceId = peerProtocol.ReadHaveMessage(reader); this.piecesDownloaded.Set(pieceId, true); if (this.BitfieldChange != null) { this.BitfieldChange(this, pieceId); } } break; case PeerMessage.Request: { int index, begin, pieceLength; peerProtocol.ReadRequestMessage(reader, out index, out begin, out pieceLength); if (this.PieceRequest != null) { this.PieceRequest(this, index, begin, pieceLength, null); } } break; case PeerMessage.Cancel: { int index, begin, pieceLength; peerProtocol.ReadCancelMessage(reader, out index, out begin, out pieceLength); if (this.PieceCancel != null) { this.PieceCancel(this, index, begin, pieceLength, null); } } break; case PeerMessage.Piece: { int index, begin, pieceLength; peerProtocol.ReadPieceMessageHeader(reader, length, out index, out begin, out pieceLength); this.numBytesDownloaded += pieceLength; byte[] data = new byte[pieceLength]; reader.Read(data, 0, data.Length); if (this.PieceIncoming != null) { this.PieceIncoming(this, index, begin, pieceLength, data); } } break; default: // received an unknown message - something has gone wrong. Disconnect the peer this.Disconnect(); break; } } } } } catch (System.Exception e) { Config.LogException(e); this.Disconnect(); } }