public static void encodeMessage(final Message message,final OutputStream out) throws IOException 
	{
		// Wrap a DataOutputStream for convenience.
		DataOutputStream dout = new DataOutputStream(out);

		// Check to see if there's more to encode.
		if (message.getLength() >= 1) 
		{
			switch (message.getType()) {
			case RUBTConstants.TYPE_CHOKE_MESSAGE: 
			{
				dout.writeInt(message.getLength());
				dout.writeByte(message.getType());
				break;
			}
			case RUBTConstants.TYPE_UNCHOKE_MESSAGE:
			{
				dout.writeInt(message.getLength());
				dout.writeByte(message.getType());
				break;
			}
			case RUBTConstants.TYPE_INTERESTED_MESSAGE:
			{
				dout.writeInt(message.getLength());
				dout.writeByte(message.getType());
				break;
			}
			case RUBTConstants.TYPE_UNINTERESTED_MESSAGE:
			{
				dout.writeInt(message.getLength());
				dout.writeByte(message.getType());
				break;
			}
			case RUBTConstants.TYPE_HAVE_MESSAGE:
			{
				HaveMessage haveMessage = (HaveMessage) message;
				dout.writeInt(haveMessage.getLength());
				dout.writeByte(haveMessage.getType());
				dout.writeInt(haveMessage.getPieceIndex());
				break;
			}
			case RUBTConstants.TYPE_BITFIELD_MESSAGE:
			{
				BitfieldMessage bitfieldMessage = (BitfieldMessage) message;
				dout.writeInt(bitfieldMessage.getLength());
				dout.writeByte(bitfieldMessage.getType());
				dout.write(bitfieldMessage.getBitfield());
				break;
			}
			case RUBTConstants.TYPE_REQUEST_MESSAGE:
			{
				RequestMessage reqMessage = (RequestMessage) message;
				dout.writeInt(reqMessage.getLength());
				dout.writeByte(reqMessage.getType());
				dout.writeInt(reqMessage.getRequest().getIndex());
				dout.writeInt(reqMessage.getRequest().getBegin());
				dout.writeInt(reqMessage.getRequest().getSize());
				break;
			}
			case RUBTConstants.TYPE_PIECE_MESSAGE:
			{
				PieceMessage pieceMessage = (PieceMessage) message;
				dout.writeInt(pieceMessage.getLength());
				dout.writeByte(pieceMessage.getType());
				dout.writeInt(pieceMessage.getRequestPiece().getIndex());
				dout.writeInt(pieceMessage.getRequestPiece().getBegin());
				dout.write(pieceMessage.requestPiece.getDownloaded());
				break;
			}
			// Error handling
			default:
				RUBTConstants.main_log.warning("Unknown message type when encoding: " + message.getType());
				break;
			}
		}
		else
		{
			//for keepAlive messages
			dout.writeInt(message.length);
		}
		// Always flush the output stream in case it's buffered.
		dout.flush();
	}